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

Paul F. Dubois Paul F. Dubois" <dubois1@llnl.gov
Sat, 5 Sep 1998 20:45:04 -0700

The intent of PyArray_FromDimsAndData is to make a Python object that uses
space you own. Python is NOT supposed to ever release it. Normally one would
create the NumPy array and then fill it up with your calculation.

-----Original Message-----
From: Scott M. Ransom <ransom@cfa.harvard.edu>
To: Aaron Watters <aaron@cs.rutgers.edu>; matrix-sig <matrix-sig@python.org>
Date: Saturday, September 05, 1998 4:34 PM
Subject: Re: [Matrix-SIG] Freeing malloc'd array in Python

>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... */
>  free(result);
>  PyArray_INCREF(arr);
>  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
>Matrix-SIG maillist  -  Matrix-SIG@python.org