Igo*_*lov 24 c++ python callback boost-python
我想从我的python代码传递回调到c ++
我希望我的代码看起来像这样:在C++中:
typedef void (*MyCallback_t) (CallbackInfo);
class MyClass
{...
void setcallback(MyCallback_t cb);
...
}
Run Code Online (Sandbox Code Playgroud)
并在python中使用它:
import mylib
def myCallback(mylib_CallbackInfo):
...
t = mylib.MyClass()
t.setcallback(myCallback)
Run Code Online (Sandbox Code Playgroud)
我在问题附近看到了一些话题,但无法解决
例如: 使用Python和C++实时处理和回调有建议使用boost :: python和关于GLI的警告,但没有示例.和这里
如何从一门外语线程(C++)调用Python函数有一个与Python代码的一部分,并以"BOOST_PYTHON_MODULE"部分没有充分说明
我还发现链接使用py_boost_function.hpp例如在Boost python howto但它没有编译和实际我无法理解如何使用它.
non*_*ont 19
好吧,我还在试图解决这个问题,但到目前为止,这里有什么工作:
#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);
Run Code Online (Sandbox Code Playgroud)
python函数从C++调用,并按预期执行.
| 归档时间: |
|
| 查看次数: |
5449 次 |
| 最近记录: |