Pim Schellart
Pim Schellart

Reputation: 735

NumPy C extension with SWIG unknown length array

I would like to wrap a C function with SWIG. The function takes a couple arrays (of the same length) as input and returns three more arrays. It is however not possible to predict the length of the return arrays beforehand and these are dynamically allocated in the function. Is it possible to wrap such a function with SWIG (using numpy.i) and if so how? A simplified function declaration looks like:

int func(double **a, double **b, long int *N, double *x, double *y, long int *Nx, long int *Ny);

Where Nx and Ny are known beforehand but N (the length of a and b) is not and a and b are allocated (with malloc) in the function.

Upvotes: 4

Views: 533

Answers (1)

Pim Schellart
Pim Schellart

Reputation: 735

It seems that SWIG (or any other Python wrapper generator for that matter) cannot do this. I ended up writing the Python wrapper by hand, which is actually quite easy, using PyArray_SimpleNew or PyArray_SimpleNewFromData to create the output arrays. With the latter one has to be extra careful so as to not generate memory leaks. After playing with it a bit I found the former combined with a simple memcpy to be safer.

Upvotes: 1

Related Questions