Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert C array to Python tuple or list with SWIG?

Tags:

python

swig

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?

like image 642
Akira Okumura Avatar asked Oct 21 '22 11:10

Akira Okumura


1 Answers

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"
like image 100
Akira Okumura Avatar answered Oct 23 '22 03:10

Akira Okumura