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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With