在 C 结构体中使用 SWIG 和指向函数的指针

问题描述 投票:0回答:3

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

测试.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
3个回答
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”我的标题而不进行修改),但我想这会做到。


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
投票

最简单的方法似乎是

  1. 创建 C++ 代码而不是 C。
  2. 克隆这个未合并的分支https://github.com/swig/swig/pull/2086并从源代码编译。
  3. 创建 python 绑定。

然后您可以使用

-c
选项来提供 C 绑定以及 python。然后您的代码将可以在 C 和 Python 中使用。

© www.soinside.com 2019 - 2024. All rights reserved.