python怎么把程序封装成函数,将python函数传递给SWIG封装的C ++代码

I am trying to wrap a C++ library for python, using SWIG. The library uses callback functions frequently, by passing callback functions of certain type to class methods.

Now, after wrapping the code, I would like to create the callback logic from python. Is this possible? Here is an experiment I was doing to find it out .. does not work at the moment.

The header and swig files are as follows:

paska.h :

typedef void (handleri)(int code, char* codename);

// handleri is now an alias to a function that eats int, string and returns void

void wannabe_handleri(int i, char* blah);

void handleri_eater(handleri* h);

paska.i :

%module paska

%{ // this section is copied in the front of the wrapper file

#define SWIG_FILE_WITH_INIT

#include "paska.h"

%}

// from now on, what are we going to wrap ..

%inline %{

// helper functions here

void wannabe_handleri(int i, char* blah) {

};

void handleri_eater(handleri* h) {

};

%}

%include "paska.h"

// in this case, we just put the actual .cpp code into the inline block ..

Finally, I test in python ..

import paska

def testfunc(i, st):

print i

print st

paska.handleri_eater(paska.wannabe_handleri(1,"eee")) # THIS WORKS!

paska.handleri_eater(testfunc) # THIS DOES NOT WORK!

The last line throws me "TypeError: in method 'handleri_eater', argument 1 of type 'handleri *'"

Is there any way to "cast" the python function to a type accepted by the SWIG wrapper?

解决方案

You can implement the callback logic in Python by using "directors".

Basically, instead of passing callback functions, you pass callback objects instead. The base object can be defined in C++ and provide a virtual callback member function. This object can then be inherited from and the callback function overwritten in Python. The inherited object can then be passed to a C++ function instead of a callback function. For this to work, you need to enable the director feature for such a callback class.

This does require changing the underlying C++ library, though.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值