簡體   English   中英

使用SWIG在Python和C之間傳遞結構

[英]Passing structure between Python and C using SWIG

我正在嘗試使用SWIG在C和Python之間傳遞一種結構。 我對Python和C完全陌生。我passing structure using SWIG搜索passing structure using SWIG ,但沒有成功。

我的代碼基於SWIG Python教程 (第55和56頁)中的示例。它應從Python獲取輸入值,然后將它們在C中乘以2,然后將結果返回給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文件中,您已經通過在%{%}聲明了new_infodelete_info函數直接將它們添加到包裝器代碼中,但是沒有告訴SWIG為這些函數生成包裝器。 %{ / %}之外再次重復代碼,或使用%inline %{ / %} 后者將代碼直接添加到包裝器,並告訴SWIG包裝它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM