[Numpy-discussion] ownership of numpy arrays

Francesc Altet faltet at carabos.com
Wed Jan 17 07:29:31 EST 2007

El dc 17 de 01 del 2007 a les 03:54 -0700, en/na josh kantor va
> I am working on a project where I am doing some interfacing with numpy 
> arrays at a C level.
> One thing that I want to do (using pyrex) is to call numpy functions, then 
> directly access the underlying double * array of the resulting ndarray and 
> operate on it in C/pyrex (I don't want to copy it). I want to ensure that 
> the underlying double * wont be deallocated until I'm ready. I was going to 
> take the resulting ndarray and set the ownership bit of the result to 0 and 
> then I would be responsible for deallocating the memory when I was ready.

Well, one possibility is to always ensure that you have a reference to
the array (using a Pyrex class variable, in case your Pyrex instance is
going to live enough, or returning it to your Python function and bound
it there to a variable until you need it). When you are done with the
array, you only have to clear all references to it (clearing the Pyrex
class variable, or doesn't returning it anymore) and Python will reclaim
the memory.

> Contrary to what I expected I noticed that it seems all numpy functions, for 
> example numpy.linalg.pinv as well as numpy.linalg.eig return matrices that 
> don't own their data.
> (If m is a numpy array)
> n=numpy.linalg.pinv(m)
> n.flags
> shows that n does not own its data.

No idea of what's happening there. numpy.sin() does seem to preserve the
ownership of the data:

>>> numpy.sin(numpy.arange(3)).flags
  OWNDATA : True
  ALIGNED : True


Francesc Altet    |  Be careful about using the following code --
Carabos Coop. V.  |  I've only proven that it works, 
www.carabos.com   |  I haven't tested it. -- Donald Knuth

More information about the NumPy-Discussion mailing list