[Matrix-SIG] returning multiple arrays from C
Kate Comer
kate@cptc.wisc.edu
Wed, 12 Aug 1998 00:55:51 -0500 (CDT)
I'm wrapping C around a set of FORTRAN spline subroutines that I want to
access from Python. Before I pull out the rest of my hair in frustration,
could someone please reveal the secret to returning more than one array
from a C extension back to python, and having the returned arrays actually
be different?
This is what I'm doing, with ~8 arrays instead of just y, dy, and yy
double *c_y, *c_yy, *c_dy;
PyObject *num_y, *num_yy, *num_dy;
PyArrayObject *arr_y, arr_yy, *num_dy;
DECLARE_INTEGER(m); \* these DECLARES *\
DECLARE_REAL_ARRAY(y, m); \* are for interface *\
DECLARE_REAL_ARRAY(yy,m); \* to FORTRAN spline *\
DECLARE_REAL_ARRAY(dy, m); \* subroutine *\
arr_y = (PyArrayObject *)PyArray_ContiguousFromObject(
num_y, PyArray_DOUBLE, 0, 0);
c_y = (double *)arr_y->data;
\* ...and the same thing two more times for the yy variables and dy
variables ...*\
for( i=0; i<m; i++ ){ \* yy and dy start out full of zeroes and *\
y[i] = *(c_x++); \* not real data, so they aren't in loop *\
}
F_SUBROUTINE_CALL(m,y,yy,dy); \* not the exact format, but I send in a *\
\* bunch of arrays and get them back again *\
for( i=0; i<m; i++ ){ \* don't need to include y because the *\
*(c_yy++) = yy[i]; \* FORTRAN subroutine didn't change it *\
*(c_dy++) = dy[i];
}
\* all is well up to here. I can printf yy and dy from within the C
program, and they are indeed different from each other and correct, so
I'm confident that the FORTRAN part is working right *\
return Py_BuildValue("OO", arr_yy, arr_dy);
Within Python I have
y = array(whatever - it's 1d)
m = len(y)
dy = zeros(m, Float)
yy = dy
yy,dy = spline_extension(y,yy,dy,m)
When I print dy and yy from python, they are BOTH yy. Interestingly,
when I change the order in the last C loop to
for( i=0; i<m; i++ ){
*(c_dy++) = dy[i];
*(c_yy++) = yy[i];
}
the arrays are still different in C, but now both are dy in python. (The
order I return the arrays to Python does not matter). This suggests some
kind of pointer problem, but I'm not sure what to do.
When I'm returning all 7 arrays, any that have the same length (all are 1-d)
are identical to any others with the same length, whether or not they're
in the same C loop.
Any hints or insight would be GREATLY appreciated.
Kate