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

Aki*_*ura 5 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};
Run Code Online (Sandbox Code Playgroud)

我可以直接从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__'
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何自动转换V为Python元组或列表?我该怎么办.i

Aki*_*ura 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"
Run Code Online (Sandbox Code Playgroud)