pass callback from python to c++ using boost::python(使用 boost::python 将回调从 python 传递到 C++)
问题描述
我想将回调从我的 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.
这篇关于使用 boost::python 将回调从 python 传递到 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 boost::python 将回调从 python 传递到 C++
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01