void * C array to a Numpy array using Swig

Jon jonathan.wright at gmail.com
Thu Jan 12 10:05:38 CET 2006


In case you find a good solution, I am also looking for one!

For now I essentially use helper functions on the c side which wrap in
SWIG to return the data as a string in python. That string can then be
converted to a numpy array using the fromstring function. This is
inefficient as it does an unnecessary copy but avoids dependence on
numeric versus numarray etc. It uses the cstring thing in SWIG (see the
manual). The library I am wrapping does not have an image struct, but
returns the data into memory that the user has to malloc.

In the swig file I have something like this, which I've simplified to
try to get to the point. It assumes you have two c functions which take
a pointer to your struct as argument, the first returns the size of the
data (what to malloc), the second copies the data into your memory
where a pointer to the memory location was second arg.

Doubtless I've introduced typos below, but hopefully you get the idea?

Good luck,

typedef struct
stuff    /* I don't know or care what is in here */
} imagefilestruct;

%extend imagefilestruct {

 [... snip constructor destructor other functions etc]

%cstring_output_allocate_size( char ** s, int *slen, free(*$1))
get_data ;

void get_data(char **s, int *slen){
   void * array;
   size_t size;
   size = libraryfunction_get_size(self);
   libraryfunc_get_data(self, array);
   *slen = size;
   *s = (char *) array;

More information about the Python-list mailing list