Python/SWIG: Output an array
python, return-value, swig
Solution
This should get you going:
/* example.c */
float * oldmain() {
static float output[] = {0.,1.};
return output;
}
You are returning a pointer here, and swig has no idea about the size of it. Plain $1_dim0 would not work, so you would have to hard code or do some other magic. Something like this:
/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern float * oldmain();
%}
%typemap(out) float* oldmain {
int i;
//$1, $1_dim0, $1_dim1
$result = PyList_New(2);
for (i = 0; i < 2; i++) {
PyObject *o = PyFloat_FromDouble((double) $1[i]);
PyList_SetItem($result,i,o);
}
}
%include "example.c"
Then in python you should get:
>> import example
>> example.oldmain()
[0.0, 1.0]
When adding typemaps you may find `-debug-tmsearch` very handy, i.e.
swig -python -debug-tmsearch example.i
Should clearly indicate that your typemap is used when looking for a suitable 'out' typemap for `float *oldmain`. Also if you just like to access c global variable array you can do the same trick using typemap for `varout` instead of just `out`.
Problem
I am trying to output an array of values from a C function wrapped using SWIG for Python. The way I am trying to do is using the following typemap. Pseudo code: ``` int oldmain() { float *output = {0,1}; return output; } ``` Typemap: ``` %typemap(out) float* { int i; $result = PyList_New($1_dim0); for (i = 0; i < $1_dim0; i++) { PyObject *o = PyFloat_FromDouble((double) $1[i]); PyList_SetItem($result,i,o); } } ``` My code compiles well, but it hangs when I run access this function (with no more ways to debug it). Any suggestions on where I am going wrong? Thanks.