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

我正在开发一个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文件应该怎么办?

最佳答案 以下宏确实有效.

%{
#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"
点赞