[Numpy-discussion] Unexpected behavior with numpy array
Travis E. Oliphant
Mon Feb 4 00:03:11 CST 2008
Damian Eads wrote:
> This is good to know because there have been a few situations when this
> would have been very useful.
> Suppose I do something like (in Python):
> import ctypes
> mylib = ctypes.CDLL('libmylib.so')
> y = mylib.get_float_array_from_c_function()
> which returns a float* as a Python int, and then I do
> nelems = mylib.get_float_array_num_elems()
> x = numpy.frombuffer(ctypes.c_buffer(y), 'float', nelems)
> This gives me an ndarray x with its (.data) buffer pointing to the
> memory address give by y. When the ndarray x is no longer referenced
> (even as another array's base), does numpy attempt to free the memory
> pointed to by y? In other words, does numpy always deallocate the
> (.data) buffer in the __del__ method? Or, does fromarray set a flag
> telling it not to?
NumPy won't free the memory unless the OWNDATA flag is set. Look at the
flags attribute. Frombuffer creates arrays that don't own there own
data, so you are safe. A reference is kept in the NumPy array to the
buffer object so it won't be deleted.
The ctypes.c_buffer is a new one for me. But, it looks like that would
work. NumPy is pretty useful for wrapping raw pointers to memory and
then playing with the data inside of Python however you would like. The
extended data-types make it very easy to do simple things with large
It's one of the not as widely understood features of NumPy.
More information about the Numpy-discussion