2009-10-17 85 views
3

我想寫一個SWIG包裝的C庫,它使用指針結構中的函數指針。我無法弄清楚如何處理包含函數指針的結構。一個簡單的例子如下。使用SWIG指針在C中的功能struct

test.i:

/* 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 

任何人都知道,如果有可能得到t.my_func(1)返回2?

謝謝!

回答

1

我找到了答案。如果我宣佈了函數指針作爲痛飲「成員函數」,似乎按預期方式工作:

%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的代碼(我寧願只是「%包含」我的頭文件而不進行修改),但是我會這樣做。

0

你忘了「return t;」在init_test()中:

#include <stdlib.h> 
#include <stdio.h> 

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; 
} 

int main(){ 
    test_struct *s=init_test(); 

    printf("%i\n", s->my_func(1)); 
} 
+0

你說得對,謝謝。對不起,這是從我使用的測試代碼抄錄我的問題時出錯。 – Steve 2009-10-18 23:54:46