[英]Passing structure between Python and C using SWIG
I'm trying to pass a structure between C and Python using SWIG. 我正在尝试使用SWIG在C和Python之间传递一种结构。 I am completely new to Python and C. I searched for
passing structure using SWIG
, without success. 我对Python和C完全陌生。我
passing structure using SWIG
搜索passing structure using SWIG
,但没有成功。
I based my code on examples from SWIG Python tutorial , page 55 and 56. It should fetch the input values from Python, multiply them by 2 in C and return the results to Python. 我的代码基于SWIG Python教程 (第55和56页)中的示例。它应从Python获取输入值,然后将它们在C中乘以2,然后将结果返回给Python。 I am getting the error
AttributeError: 'module' object has no attribute 'new_info
. 我收到错误
AttributeError: 'module' object has no attribute 'new_info
。
sample.c 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 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;
Command executed to build the wrapper: 执行命令以构建包装器:
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 error: 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'
>>>
In the sample.i
file, you've added the new_info
and delete_info
functions to the wrapper code directly by declaring it within %{
and %}
, but did not tell SWIG to generate wrappers for those functions. 在
sample.i
文件中,您已经通过在%{
和%}
声明了new_info
和delete_info
函数直接将它们添加到包装器代码中,但是没有告诉SWIG为这些函数生成包装器。 Either repeat the code again outside the %{
/ %}
, or use %inline %{
/ %}
. 在
%{
/ %}
之外再次重复代码,或使用%inline %{
/ %}
。 The latter adds the code directly to the wrapper as well as tells SWIG to wrap it. 后者将代码直接添加到包装器,并告诉SWIG包装它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.