c python boost.python_通过回调从python到c + +使用boost :: python

1586010002-jmsa.png

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.

解决方案

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(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.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值