Python / SWIG: array output

I am trying to derive an array of values ​​from a C function terminated using SWIG for Python. The way I'm trying to do this is to use the following card.

Pseudocode:

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 freezes when I start accessing this function (without additional ways to debug it).

Any suggestions on where I am going wrong?

Thank.

+5
source share
2 answers

This should make you:

/* example.c */

float * oldmain() {
    static float output[] = {0.,1.};
    return output;
}

You are returning a pointer here, and swig has no idea about its size. Plain $ 1_dim0 will not work, so you have to make hard code or do some other magic. Something like that:

/* 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 can find it -debug-tmsearchvery convenient, i.e.

swig -python -debug-tmsearch example.i

, 'out' typemap float *oldmain. , c, , typemap varout, out.

+5

- , :

%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;
}
%}

, size_t *len, . Python %typemap(out) .

+5

All Articles