[Numpy-discussion] Unexpected behavior with numpy array
Robert Kern
robert.kern@gmail....
Mon Feb 4 00:31:28 CST 2008
Travis E. Oliphant wrote:
> 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.
Unfortunately, it doesn't work the way it is used in Damian's example. It is a
deprecated alias for create_string_buffer(), which creates a ctypes array of
c_char from a string or a size. It does not make a buffer object from a ctypes
pointer object or an address.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion
mailing list