使用boost python将现有的C ++指针传递给python回调

时间:2016-11-14 15:53:35

标签: c++ boost boost-python

我有一个抽象的C ++类,我通过boost python公开:

expose.h:

struct I {
    virtual int compute() = 0;
};

BOOST_PYTHON_MODULE( my_module )
{
    boost::python::class_< I, boost::noncopyable >( "I", boost::python::no_init )
        .def( "compute", &I::compute );
}

从c ++中调用的Python代码:

callback.py:

import my_module

def MyPythonFunc(a):
     return a.compute()

最后,在我的主要cpp代码中,我有一个指针,我想传递给python函数:

consume.cpp:

struct B : public I {
    virtual int compute() override { return 42; }
}

B *ptr = new B;

boost::python::object main = boost::python::import( "__main__" );
boost::python::object global( main.attr( "__dict__" ) );
boost::python::object result = boost::python::exec_file( "callback.py", global, global );
boost::python::object fn = global["MyPythonFunc"];

if (!fn.is_none()) {
    // pass ptr to MyPythonFunc, ideally wrapped in a shared_ptr?
}

这似乎是一个典型的场景,但我找不到任何能解决它的东西。感谢。

0 个答案:

没有答案