简体   繁体   English

Boost.Python:从C ++调用虚拟函数

[英]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. 我不是在寻求虚函数公开给Python的帮助,我想知道如何从C ++方面调用所述虚函数。 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? 关于如何将Base*捕获到派生类型的任何建议,以便在执行base->func()调用Python函数? The Boost docs only describe how to expose the virtual functions to Python, not how to call their redefinitions from C+. Boost文档仅描述了如何将虚函数公开给Python,而不描述如何从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. 您必须将包装器添加到python类中,随后将从该包装器派生python类。 here, under 1. I explained briefly how it works. 在这里,在1.下,我简要解释了它是如何工作的。 So, to call python-override of a c++ virtual method, use get_override and call the returned object with () . 因此,要调用c ++虚拟方法的python-override,请使用get_override并使用()调用返回的对象。

For some code, see eg here , where Predicate and PredicateWrap are defined, but then PredicateWrap is really exposed to python; 对于某些代码,请参见例如here ,其中定义了PredicatePredicateWrap ,但随后PredicateWrap 才真正暴露给python。 calling the overridden methods is done here , but that is hidden to the user. 调用覆盖的方法在这里完成,但是对用户是隐藏的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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