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

2022-01-03 00:00:00 python callback c++ 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来自外语线程(C++)的函数没有完整的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 但它没有编译,实际上我无法理解如何使用它.

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.

相关文章