문제

I am developing a C++/Python library project which uses SWIG when converting the C++ code to the Python library. In one of C++ headers, I have some global constant values as below.

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

I can use V0 to V3 directly from Python, but cannot access the entries in 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__'

Could anyone tell me how to automatically convert V to a Python tuple or list? What should I do in my .i file?

도움이 되었습니까?

해결책

The following macro did work.

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

다른 팁

If you don't want to create a typemap you can use the swig library carrays.i to access the entries in a C-type array.

your .i file would be something like:

%{
#include "myheader.h"
%}

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

%include "myheader.h"

and then you could access mylibrary.V[0] in python with:

>>> intArray_getitem(mylibrary.V, 0)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top