Python 在C结构中使用带函数指针的SWIG

Python 在C结构中使用带函数指针的SWIG,python,c,function,pointers,swig,Python,C,Function,Pointers,Swig,我正在尝试为C库编写一个SWIG包装器,它使用指向其结构中函数的指针。我不知道如何处理包含函数指针的结构。下面是一个简化的例子 测试一: /* test.i */ %module test %{ typedef struct { int (*my_func)(int); } test_struct; int add1(int n) { return n+1; } test_struct *init_test() { test_struct *t = (test_struc

我正在尝试为C库编写一个SWIG包装器,它使用指向其结构中函数的指针。我不知道如何处理包含函数指针的结构。下面是一个简化的例子

测试一:

/* test.i */

%module test
%{

typedef struct {
    int (*my_func)(int);
} test_struct;

int add1(int n) { return n+1; }

test_struct *init_test()
{
    test_struct *t = (test_struct*) malloc(sizeof(test_struct));
    t->my_func = add1;
}
%}

typedef struct {
    int (*my_func)(int);
} test_struct;

extern test_struct *init_test();
示例会话:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.init_test()
>>> t
<test.test_struct; proxy of <Swig Object of type 'test_struct *' at 0xa1cafd0> >
>>> t.my_func
<Swig Object of type 'int (*)(int)' at 0xb8009810>
>>> t.my_func(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'PySwigObject' object is not callable
python2.6.2(release26maint,2009年4月19日,01:56:41)
[GCC 4.3.3]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>导入测试
>>>t=test.init_test()
>>>t
>>>t.my_func
>>>t.my_func(1)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“PySwigObject”对象不可调用
有人知道有没有可能让t.my_func(1)返回2

谢谢

在init_test()中忘记了“return t;”:

#包括
#包括
类型定义结构{
int(*my_func)(int);
}测试结构;
intadd1(intn){返回n+1;}
test_struct*init_test(){
test_struct*t=(test_struct*)malloc(sizeof(test_struct));
t->my_func=add1;
返回t;
}
int main(){
test_struct*s=init_test();
printf(“%i\n”,s->my_func(1));
}

我找到了答案。如果我将函数指针声明为SWIG“member function”,它似乎可以按预期工作:

%module test
%{

typedef struct {
  int (*my_func)(int);
} test_struct;

int add1(int n) { return n+1; }

test_struct *init_test()
{
    test_struct *t = (test_struct*) malloc(sizeof(test_struct));
    t->my_func = add1;
    return t;
}

%}

typedef struct {
    int my_func(int);
} test_struct;

extern test_struct *init_test();
会议:

$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.init_test()
>>> t.my_func(1)
2

我希望能有一些不需要编写任何自定义SWIG特定代码的东西(我更喜欢不加修改地“%include”我的标题),但我想这样就可以了。

你说得对,谢谢。很抱歉,从我使用的测试代码中抄写我的问题时出错。
$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.init_test()
>>> t.my_func(1)
2