Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swig, returning an array of doubles

I know, there are often many ways to solve certain problems. But here I know which way I want to have it, but I am unable to make it work with Python and SWIG...

I have a C-function, which returns me an array of double values:

double *my(int x)
{
   double a,b,*buf;
   buf = malloc (x * sizeof(double));
   a=3.14;
   b=2.7;
   buf[0]=a;
   buf[1]=b;
   return buf;
}

Here, I definitively want to have the array as a return value. Not, as in many examples a 'void' function, which writes into an input array. Now, I would like to get a SWIG-python wrapper, which might be used as:

>>> import example
>>> print example.my(7)
[3.14,2.7]

Whatever I do, I have some conceptual problems here - I always get s.th. like <Swig Object of type 'double *' at 0xFABCABA12>

I tried to define some typemaps in my swg file:

%typemap(out) double [ANY] {
  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);
  }
}

But still I am unable to get out my results as required. Does anyone have a simple code-example to achieve this task?

like image 452
user701370 Avatar asked Apr 28 '11 17:04

user701370


1 Answers

The first problem is that your typemap doesn't match, you'll need a %typemap(out) double * { ... } since your function returns a pointer to double and not a double array.

If your list is of fixed size (i.e. an integer literal) as in the example you gave (which I assume is not what you want) you could simply change the typemap as I gave above and exchange $1_dim0 for the fixed size.

Otherwise your problem is that your %typemap(out) double * cannot possibly know the value of your parameter int x. You could return a struct that carries both the pointer and the size. Then you can easily define a typemap to turn that into a list (or a NumPy array, see also my response to Wrap C struct with array member for access in python: SWIG? cython? ctypes?).

Incidentally it's not possible to return a fixed sized array in C (see also this answer: Declaring a C function to return an array), so a %typemap(out) double [ANY] { ... } can never match.

like image 182
kynan Avatar answered Oct 10 '22 01:10

kynan