使用boost::python从python传递回调到c++

pass callback from python to c++ using boost::python

本文关键字:python 回调 c++ boost 使用      更新时间:2023-10-16

我想通过回调从我的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