使用 SWIG 在 Python 和 C 之间传递结构

Passing structure between Python and C using SWIG

我正在尝试使用 SWIG 在 C 和 Python 之间传递一个结构。我对 Python 和 C 完全陌生。我搜索了 passing structure using SWIG,但没有成功。

我的代码基于 SWIG Python tutorial,第 55 和 56 页的示例。它应该从 Python 获取输入值,在 C 中将它们乘以 2,然后 return 结果至 Python。我收到错误 AttributeError: 'module' object has no attribute 'new_info.

sample.c

#include <stdio.h>
#include "sample.h"

struct info sample;

void getstruct (struct info *sample);

void getstruct (struct info *sample) {

   int i = 0;
   int j = 0;
   int k = 0;
   int l = 0;

   i = 2 * sample->i;
   j = 2 * sample->j;
   k = 2 * sample->k;
   l = 2 * sample->l;

   sample->i = i;
   sample->j = j;
   sample->k = k;
   sample->l = l;

   return(&sample);

}

sample.i

%module sample
%{
typedef struct
{
   int i;
   int j;
   int k;
   int l;
} info;

extern void getstruct (struct info *sample);

info *new_info(int i, int j, int k, int l) {
    info *in = (info *) malloc(sizeof(info));
    in->i = i;
    in->j = j;
    in->k = k;
    in->l = l;
    return in;
}

void delete_info(info *in) {
    free(in);
}
%}

extern void getstruct (struct info *sample);
typedef struct
{
   int i;
   int j;
   int k;
   int l;
} info;

构建包装器所执行的命令:

swig -python sample.i
gcc -fPIC -c sample.c sample_wrap.c -I/usr/include/python2.7
ld -shared sample.o sample_wrap.o -o _sample.so

Python 错误:

[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sample
>>>
>>> print sample
<module 'sample' from 'sample.pyc'>
>>> print sample.getstruct(1,2,3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getstruct() takes exactly 1 argument (4 given)
>>> v = new_info(1,2,3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'new_info' is not defined
>>> v = sample.new_info(1,2,3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'new_info'
>>>

sample.i 文件中,您通过在 %{ 和 [=14= 中声明,直接将 new_infodelete_info 函数添加到包装代码中],但没有告诉 SWIG 为这些函数生成包装器。在 %{/%} 之外再次重复代码,或者使用 %inline %{/%}。后者将代码直接添加到包装器并告诉 SWIG 包装它。