开发者

Boost.Python: Calling virtual functions from C++

I'm not looking for help on exposing virtual functions to Python, I would like to know how I can call the said virtual functions from the C++ side. Consider this...

// ====================
// C++ code
// --------------------

struct Base
{
    virtual void func() {
        cout << "Hello from C++!";
    }
};

BOOST_PYTHON_MODULE(name)
{
    // Expose the class and its virtual function here
}


// ====================
//   Python code
// --------------------

from name import Base

class Deriv(Base):
    de开发者_高级运维f func():
        print('Hello from Python!')

Any advice on how I might grab a Base* to the derived type such that when I do base->func(), the Python function is called? The Boost docs only describe how to expose the virtual functions to Python, not how to call their redefinitions from C+.


Your approach will not work in such a simple way; you have to add wrapper to your python class, from which python class will be subsequently derived. here, under 1. I explained briefly how it works. So, to call python-override of a c++ virtual method, use get_override and call the returned object with ().

For some code, see e.g. here, where Predicate and PredicateWrap are defined, but then PredicateWrap is really exposed to python; calling the overridden methods is done here, but that is hidden to the user.


I think you just call extract<Base*>(obj) where obj is python::object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜