7
votes

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.

2
Can you share your Makefile or similar? You might find Cython easier than SWIG, unless you might do more languages than just Python. - user1277476
Thanks, Oleksiy's answer solved my issue, but as you said, Cython seems to be easier and I am exploring that. Thanks again. - SEU

2 Answers

6
votes

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.

7
votes

The easiest way to allow the length to vary is to add another output parameter that tells you the size of the array too:

%module test

%include <stdint.i>

%typemap(in,numinputs=0,noblock=1) size_t *len  {
  size_t templen;
  $1 = &templen;
}

%typemap(out) float* oldmain {
  int i;
  $result = PyList_New(templen);
  for (i = 0; i < templen; i++) {
    PyObject *o = PyFloat_FromDouble((double)$1[i]);
    PyList_SetItem($result,i,o);
  }
}

%inline %{
float *oldmain(size_t *len) {
  static float output[] = {0.f, 1.f, 2, 3, 4};
  *len = sizeof output/sizeof *output;
  return output;
}
%}

This is modified from this answer to add size_t *len which can be used to return the length of the array at run time. The typemap completely hides that output from the Python wrapper though and instead uses it in the %typemap(out) instead of a fixed size to control the length of the returned list.