将python函数传递给SWIG封装的C ++代码 [英] Passing python functions to SWIG wrapped C++ code
问题描述
我试图用一个C ++库为python,使用SWIG。通过将某些类型的回调函数传递给类方法,库经常使用回调函数。
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.
现在,从python创建回调逻辑。这可能吗?
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.
头文件和swig文件如下:
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 ..
最后,我在python中测试..
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!
最后一行抛出TypeError:在方法'handleri_eater',类型'handleri * '
The last line throws me "TypeError: in method 'handleri_eater', argument 1 of type 'handleri *'"
有没有办法将python函数转换为SWIG包装器接受的类型?
Is there any way to "cast" the python function to a type accepted by the SWIG wrapper?
推荐答案
您可以使用director。
基本上,不是传递回调函数,而是传递回调对象。基本对象可以在C ++中定义,并提供一个 virtual
回调成员函数。这个对象可以继承自Python中的覆盖的回调函数。继承的对象然后可以传递到C ++函数而不是回调函数。为了这个工作,你需要为这样的回调类启用导演功能。
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.
这需要改变底层的C ++库。
This does require changing the underlying C++ library, though.
这篇关于将python函数传递给SWIG封装的C ++代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!