通过回调从python到c + +使用boost :: python [英] pass callback from python to c++ using boost::python
问题描述
我想将回调从我的Python代码传递给c ++
I want to pass callback from my python code to c++
我想我的代码看起来像这样:
在C ++中:
I want my code look something like this: In C++ :
typedef void (*MyCallback_t) (CallbackInfo);
class MyClass
{...
void setcallback(MyCallback_t cb);
...
}
并在python中使用它:
And to use it in python :
import mylib
def myCallback(mylib_CallbackInfo):
...
t = mylib.MyClass()
t.setcallback(myCallback)
一些主题在我的问题附近,但无法解决
I saw some topics near my problem but couldn't solve it
例如:
使用Python和C ++的实时处理和回调建议使用boost :: python和关于GLI的警告,但没有示例。
此处
For example here : Realtime processing and callbacks with Python and C++ there is advice to use boost::python and warning about GLI but no examples. And here
没有对python代码部分和BOOST_PYTHON_MODULE部分的完整描述
How to call a python function from a foreign language thread (C++) there is no full description with python code part and with "BOOST_PYTHON_MODULE" part
我还在 Boost python howto中找到了使用py_boost_function.hpp的链接,但它没有编译,实际上我不明白如何使用它。
I also found link to use py_boost_function.hpp for example in Boost python howto but it didn't compile and actualy I couldn't understand how to use it.
推荐答案
仍然试图找出这一点,但这里是为我工作到目前为止:
Ok, I'm still trying to figure this out too, but here's whats working for me so far:
#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 ++调用,并按预期执行。
The python function is invoked from C++, and executes as expected.
这篇关于通过回调从python到c + +使用boost :: python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!