简体   繁体   English

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

[英]pass callback from python to c++ using boost::python

I want to pass callback from my python code to c++我想将回调从我的 python 代码传递给 C++

I want my code look something like this: In C++ :我希望我的代码看起来像这样:在 C++ 中:

typedef void (*MyCallback_t) (CallbackInfo);

class MyClass
{...
   void setcallback(MyCallback_t cb);
 ...
}

And to use it in python :并在 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我在我的问题附近看到了一些主题,但无法解决它

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.例如: 使用 Python 和 C++ 进行实时处理和回调,建议使用 boost::python 并警告有关 GLI 但没有示例。 And here和这里

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 如何从外语线程(C++)调用python函数没有python代码部分和“BOOST_PYTHON_MODULE”部分的完整描述

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.我还在Boost python howto 中找到了使用 py_boost_function.hpp 的链接,但它没有编译,实际上我无法理解如何使用它。

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);

The python function is invoked from C++, and executes as expected. python 函数从 C++ 调用,并按预期执行。

These test files from the boost::python source code repository contains great examples about how to pass callbacks from Python into C++: boost::python 源代码存储库中的这些测试文件包含有关如何将回调从 Python 传递到 C++ 的很好的示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM