/* simple example of how to pass a multidimensional numarray array from python to C, and be able to address it as A[i][j]. from numarray import * a = arange(36) a.shape = (6,6) import arraylib arraylib.print(a) */ #include "Python.h" #include "numarray/numarray.h" #include "numarray/libnumarray.h" static PyObject *dump(PyObject *self, PyObject *args) { PyObject *oArray; PyArrayObject *pArray; double **cArray; int nx, ny; double *pData; int i, j; /* parse the argument list -- only take one argument, a numarray array */ if (!PyArg_ParseTuple(args, "O", &oArray)) return NULL; pArray = NA_InputArray(oArray, tFloat64, NUM_C_ARRAY); if (!pArray) { printf("ERROR in arraylib.print: invalid parameters\n"); return NULL; } /* at the moment, we expect the array to be two-dimensional. It is straightforward to extend this to higher dimensions */ if (pArray->nd != 2) { printf("ERROR in arraylib.print: array must have 2 dimensions\n"); return NULL; } nx = pArray->dimensions[0]; ny = pArray->dimensions[1]; /* we could access the array now, through one-dimensional indexing * * pData = (double *) pArray->data; * for (i = 0; i < nx*ny; i++) { * printf ("%f\n", pData[i]); * } */ /* but instead, we want to be able to index it as a multidimensional C array. so we use a double ** pointer to make indexing easier */ cArray = (double **) malloc(sizeof(double *)*nx); for (i = 0; i < nx; i++) { cArray[i] = (double *) NA_OFFSETDATA(pArray) + i*ny; } /* now cArray[i][j] points to the relevant portions of the pArray data field */ for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { printf("%f ", cArray[i][j]); } printf("\n"); } free(cArray); Py_XDECREF(pArray); return Py_BuildValue("i", 1); } static PyMethodDef arraylibmethods[] = { {"dump", dump, METH_VARARGS}, {NULL, NULL} }; initarraylib(void) { Py_InitModule("arraylib", arraylibmethods); import_libnumarray(); }