[英]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”部分的完整描述
我還在Boost python howto 中找到了使用 py_boost_function.hpp 的鏈接,但它沒有編譯,實際上我無法理解如何使用它。
好的,我也在努力解決這個問題,但到目前為止,這是對我有用的:
#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++ 調用,並按預期執行。
boost::python 源代碼存儲庫中的這些測試文件包含有關如何將回調從 Python 傳遞到 C++ 的很好的示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.