使用痛饮与指针在C结构功能 [英] Using SWIG with pointer to function in C struct

查看:111
本文介绍了使用痛饮与指针在C结构功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个使用指针在其结构功能的C库一大口包装。我无法弄清楚如何处理包含函数指针结构。一个简单的例子如下:

I'm trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs. I can't figure out how to handle structs that contain function pointers. A simplified example follows.

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?

谢谢!

推荐答案

我找到了答案。如果我声明函数指针作为痛饮成员函数,似乎按预期方式工作:

I found an answer. If I declare the function pointer as a SWIG "member function", it seems to work as expected:

%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

我希望的东西,就不需要编写任何客户定制痛饮,code(我preFER为%包括我的头不加修改),但这会做我猜。

I was hoping for something that wouldn't require writing any custom SWIG-specific code (I'd prefer to just "%include" my headers without modification), but this will do I guess.

这篇关于使用痛饮与指针在C结构功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆