Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

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

I want to pass callback from my python code to c++

I want my code look something like this: In C++ :

typedef void (*MyCallback_t) (CallbackInfo);

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

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

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...