使用boost::python从python传递回调到c++
pass callback from python to c++ using boost::python
我想通过回调从我的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 how中,但它没有编译,实际上我无法理解如何使用它。
好的,我还在努力弄清楚这个,但这是目前为止对我有效的:
#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);
从c++中调用python函数,并按预期执行。
这些来自boost::python源代码存储库的测试文件包含了关于如何从python传递回调到c++的很好的示例:
- https://github.com/boostorg/python/blob/develop/test/callbacks.cpp
- https://github.com/boostorg/python/blob/develop/test/callbacks.py
相关文章:
- 如何为Python Swigged C++对象创建和分配回调函数
- 通过 Boost Python 将 Python 函数转换为 C++,用作回调
- Python ctypes,回调函数增强类型是C++参考
- 在 Python 中打开 Maya callBacks 或C++查询内存中的所有回调
- 可以提升::p ython将对象的所有权传递给python回调函数
- boost::python:使用回调
- 如何使python函数作为c++函数的回调
- 无法停止来自python C扩展的python回调
- Cython:在DLL中注册用于回调的Python函数
- 在 Python 中扩展的 C++ 类中的 Seg 错误回调问题
- 在Python中使用回调时出错
- 从c++(或C)回调调用python方法
- Boost Python回调返回auto_ptr删除对象
- 嵌入python + numpy代码到c++ dll回调
- 使用boost::python从python传递回调到c++
- 提振.Python:类函数的回调
- Boost Python,传播c++回调到Python导致分段错误
- 当函数接受非平凡的参数时,C++通过SWIG用python回调
- Cython使用python-c-api调用回调segfault
- C++对Python的扩展:如何在C回调中确定Python函数名