【问题标题】:Using SWIG with pointer to function in C struct在 C 结构中使用带有指向函数的指针的 SWIG
【发布时间】:2009-10-17 21:36:33
【问题描述】:

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

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?

谢谢!

【问题讨论】:

    标签: python c function pointers swig


    【解决方案1】:

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

    %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”我的标头而不进行修改),但我猜这会做到。

    【讨论】:

      【解决方案2】:

      你忘记了“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) );
      }
      

      【讨论】:

      • 你是对的,谢谢。抱歉,从我使用的测试代码转录我的问题时出错。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多