简体   繁体   中英

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):
    def 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+.

我认为您只是调用extract<Base*>(obj) ,其中objpython::object

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM