Estoy tratando de escribir un contenedor SWIG para una biblioteca de C que utiliza punteros a funciones en sus estructuras. No puedo averiguar cómo manejar estructuras que contienen punteros de función. Un ejemplo simplificado sigue.
prueba.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();
sesión de muestra:
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 > >>> t.my_func >>> t.my_func(1) Traceback (most recent call last): File "", line 1, in TypeError: 'PySwigObject' object is not callable
¿Alguien sabe si es posible que t.my_func (1) devuelva 2?
¡Gracias!
Encontré una respuesta. Si declaro el puntero a la función como una “función miembro” de SWIG, parece funcionar como se esperaba:
%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();
Sesión:
$ 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
Esperaba algo que no requeriría escribir ningún código personalizado específico de SWIG (preferiría simplemente “% incluir” mis encabezados sin modificación), pero supongo que esto sí lo hará.
Te olvidas de “devolver t;” en init_test ():
#include #include 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) ); }