使用boost::python从Python传递回调给C++
我想把回调函数从我的Python代码传递到C++代码中。
我希望我的代码看起来像这样:
在C++中:
typedef void (*MyCallback_t) (CallbackInfo);
class MyClass
{...
void setcallback(MyCallback_t cb);
...
}
然后在Python中使用它:
import mylib
def myCallback(mylib_CallbackInfo):
...
t = mylib.MyClass()
t.setcallback(myCallback)
我看到一些和我问题相关的讨论,但还是没能解决。
比如这里有个帖子: 使用Python和C++进行实时处理和回调,里面建议使用boost::python,并警告关于GLI的问题,但没有给出示例。
还有这里:
如何从外部语言线程(C++)调用Python函数,里面没有完整的描述,包括Python代码部分和“BOOST_PYTHON_MODULE”部分。
我还找到一个链接,提到可以使用py_boost_function.hpp,具体在这个Boost python使用指南中,但我编译不通过,实际上我也不太明白怎么用。
2 个回答
2
这些来自boost::python源代码库的测试文件,里面有很好的例子,展示了如何把Python中的回调函数传递到C++里:
22
好的,我也在努力弄明白这个问题,不过到目前为止,这里是我找到的有效方法:
#this is the variable that will hold a reference to the python function
PyObject *py_callback;
#the following function will invoked from python to populate the call back reference
PyObject *set_py_callback(PyObject *callable)
{
py_callback = callable; /* Remember new callback */
return Py_None;
}
...
#Initialize and acquire the global interpreter lock
PyEval_InitThreads();
#Ensure that the current thread is ready to call the Python C API
PyGILState_STATE state = PyGILState_Ensure();
#invoke the python function
boost::python::call<void>(py_callback);
#release the global interpreter lock so other threads can resume execution
PyGILState_Release(state);
这个Python函数是从C++中调用的,运行起来也很正常。