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

5

我正在开发一个C++/Python库项目,使用SWIG将C++代码转换为Python库。在其中一个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个回答

3
以下宏已经起作用。
%{
#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"

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接