[Matrix-SIG] Freeing malloc'd array in Python

Scott M. Ransom ransom@cfa.harvard.edu
Sat, 05 Sep 1998 23:32:42 +0000

Aaron Watters wrote:

> ...If you just need fresh memory maybe
> you could allocate a "blob" as a numpy array and then use the
> internal buffer as storage, perhaps obviating the need to do a full
> pyobject implementation... If you need to wrap preallocated
> structures, then you gotta do the pyobject thing -- but be careful
> if the structure is referenced outside of the "python domain".

Well I got rid of the memory leak by using a different routine to
allocate the PyArrayObject.  Instead of doing the following in the
wrapper function:

  arr = (PyArrayObject *)PyArray_FromDimsAndData(1, (int *)&n,
PyArray_DOUBLE, \
                                                 (char *) result);

I used the following to allocate a PyArrayObect of known size and then
copied the data into the data portion of the PyArrayObject.  Finally, I
lose the memory leak by freeing the now useless array that came from my
'C' function.  This works (including proper memory management of the
array in Python),  but seems kind of inelegant since I have to copy a
perfectly good block of memory into a different location.

Note:  'result' is a double precision vector that was allocated in a 'C'

  arr = (PyArrayObject *)PyArray_FromDims(1, (int *)&n, PyArray_DOUBLE);

  if (arr == NULL) return NULL;

  /* Have to copy the data, until I figure out a better way... */

  memcpy(arr->data, (char *)result, n*arr->descr->elsize);

  /* Free the malloced array from the 'C' routine... */


  return (PyObject *)arr;

Does anyone know if I can perform a free(arr->data) and then a arr->data
= result instead?  That would get rid of the memcpy() and keep the
original result array.

> Also maybe look into SWIG.

I already am.  The reason I am doing this whole thing is to generate
SWIG templates for Numeric Python for my code...

Thanks for the help.


Scott M. Ransom
Phone:  (580) 536-7215             Address:  703 SW Chaucer Cir.
email:  ransom@cfa.harvard.edu               Lawton, OK  73505
PGP Fingerprint: D2 0E D0 10 CD 95 06 DA  EF 78 FE 2B CB 3A D3 53