[Numpy-discussion] swig numpy2carray converters

Bill Spotz wfspotz at sandia.gov
Fri Nov 30 11:26:26 EST 2007


The numpy array is created using PyArray_SimpleNewFromData().  From  
the Guide to NumPy, "[y]ou should ensure that the provided memory is  
not freed while the returned array is in existence."  That is, numpy  
does not try to deallocate the memory when the ndarray object is  
destroyed, but it also *assumes* that you do not deallocate it  
yourself.  Since numpy.i is dealing with essentially non-reference- 
counted pointers to raw buffers, I have no way to guarantee this.

I think the typical use case will be that you wrap a class that  
allocates a chunk of memory (that it deallocates when it gets  
destroyed).  It gives you a view to that data, which we then  
encapsulate with a numpy array.  If you create such an object,  
extract such an array, and then destroy the object but not the array,  
then the numpy array will point to garbage, possibly resulting in a  
segmentation fault when you try to access it.  The only answer I know  
of is to not destroy the object before the array.

There are situations where you just can't get around it (based on how  
the C++ class was designed).  But if you can get around it, you should.

On Nov 30, 2007, at 3:55 AM, Sebastian Haase wrote:

> Could you elaborate on what you mean by "potentially dangerous" !?
> Is it important *how* the internal data memory was allocated ? Using
> "new" or using "malloc" ?
> This would require (following the standard) that the correct, i.e.
> corresponding, delete[] or free()  [respectively], de-allocation
> function is called.
>
> When is the memory being freed ?
> Is (or can !) python taking ownership of the memory and calls the
> correct "free"/"delete[]"  function ?

** Bill Spotz                                              **
** Sandia National Laboratories  Voice: (505)845-0170      **
** P.O. Box 5800                 Fax:   (505)284-0154      **
** Albuquerque, NM 87185-0370    Email: wfspotz at sandia.gov **







More information about the NumPy-Discussion mailing list