[Numpy-discussion] Help with PyArrayObject and C Arrays.

Andrea Riciputi ariciputi at pito.com
Wed Nov 19 08:26:17 CST 2003


Hi,
I've written some C code for number crunching that uses the following 
structure for simulating 2-dimensional arrays (i.e. matrices):

typedef struct {
   double **aa;
   int nrows;
   int ncols;
} Array2d;

In order to read these C arrays in Python+Numeric and vice versa, I've 
written some wrapping code, but I'm not so sure it's correct. In 
particular I'm concerned in memory leakage, I don't know if I've 
understood correctly how PyArray_FromDimsAndData works and if I've 
choose the best way to solve the problem. My code follows.

Thanks for help!
	Andrea.

C --> Python
============

  static PyObject *Array2d_2_PyArrayObject(Array2d *input) {
     int ndims[2];
     PyArrayObject *result;

     if (!input) return NULL;

     ndims[0] = input->nrows;
     ndims[1] = input->ncols;
     result = (PyArrayObject *) PyArray_FromDimsAndData(2, ndims, 
PyArray_DOUBLE, (char *) input->aa[0]);

     free(input->aa);
     free(input);

     return PyArray_Return(result);
   }

Python --> C
============

   static Array2d *PyList_2_Array2d(PyObject *input) {
     Array2d *result;

     if (!PySequence_Check(input)) {
       PyErr_SetString(PyExc_TypeError,"Expected a sequence");
       return NULL;
     }

     result = (Array2d *) malloc(sizeof(Array2d));
     PY_CHECK_ALLOC(result);

     if (PyArray_As2D((PyObject **) &input, (char ***) &(result->aa), 
&(result->nrows), &(result->ncols), PyArray_DOUBLE) != 0) {
       PyErr_SetString(PyExc_MemoryError,"No heap space for data");
       return NULL;
     }

     return result;
   }



---
Andrea Riciputi

"Science is like sex: sometimes something useful comes out,
   but that is not the reason we are doing it" -- (Richard Feynman)





More information about the Numpy-discussion mailing list