如何使用SWIG将C数组转换为Python元组或列表?

时间:2014-04-04 02:18:15

标签: python swig

我正在开发一个C ++ / Python库项目,它在将C ++代码转换为Python库时使用SWIG。在C ++标题之一中,我有一些全局常量值,如下所示。

const int V0 = 0;
const int V1 = 1;
const int V2 = 2;
const int V3 = 3;
const int V[4] = {V0, V1, V2, V3};

我可以直接从Python使用V0到V3,但无法访问V中的条目。

>>> import mylibrary
>>> mylibrary.V0
0
>>> mylibrary.V[0]
<Swig Object of type 'int *' at 0x109c8ab70>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'SwigPyObject' object has no attribute '__getitem__'

有人能告诉我如何自动将V转换为Python元组或列表吗?我应该在.i文件中做什么?

2 个答案:

答案 0 :(得分:2)

以下宏确实有用。

%{
#include "myheader.h"
%}

%define ARRAY_TO_LIST(type, name)
%typemap(varout) type name[ANY] {
  $result = PyList_New($1_dim0);
  for(int i = 0; i < $1_dim0; i++) {
    PyList_SetItem($result, i, PyInt_FromLong($1[i]));
  } // i
}
%enddef

ARRAY_TO_LIST(int, V)

%include "myheader.h"

答案 1 :(得分:0)

如果您不想创建类型图,可以使用swig库carrays.i访问C类型数组中的条目。

你的.i文件会是这样的:

%{
#include "myheader.h"
%}

%include "carrays.i"
%array_functions(int,intArray)

%include "myheader.h"

然后你可以在python中使用:

访问mylibrary.V [0]
>>> intArray_getitem(mylibrary.V, 0)