How to convert a C array to a Python tuple or list using SWIG?

I am developing a C ++ / Python library project that uses SWIG when converting C ++ code to a Python library. In one of the C ++ headers, I have some global constant values, as shown 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 for V3 directly from Python, but cannot access the elements 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__'

Can someone tell me how to automatically convert Vto a tuple or list of Python? What to do in the file .i?

+4
source share
2 answers

The following macro worked.

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

, swig carrays.i C .

.i :

%{
#include "myheader.h"
%}

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

%include "myheader.h"

mylibrary.V [0] python :

>>> intArray_getitem(mylibrary.V, 0)
0

Source: https://habr.com/ru/post/1534951/


All Articles