[Numpy-discussion] __array_interface__ / __array_struct__
Travis E. Oliphant
Tue Jan 22 16:20:56 CST 2008
Thomas Heller wrote:
> Travis E. Oliphant schrieb:
>> Thomas Heller wrote:
>>> I am experimenting with implementing __array_interface__ and/or __array_struct__
>>> properties for ctypes instances, and have problems to create numpy arrays
>>> from them that share the memory. Probably I'm doing something wrong;
>>> what is the correct function in numpy to create these shared objects?
>>> I am using numpy.core.multiarray.array(ctypes-object), is that correct?
>> Yes, this should work, as the array function goes through several checks
>> including looking for the __array_struct__ and/or __array_interface__
>> attributes. If you can point me to the code, I can probably help.
> The pure-python code, using __array_interface__, is here:
> Use a webbrowser to view or download it, or an svn client
> to checkout a copy. I use it like this:
> from ctypes_array mport as_ctypes, as_array
> c_array = (c_double * 3)()
> numpy_array = as_array(c_array)
> numpy_array = zeros(32)
> c_array = as_array(numpy_array)
> In the former example the objects to bot share memory, in the
> latter example they do.
> I also have an extension in the works that uses __array_struct__,
> but this is not yet uploaded.
This is all very good. The only thing missing that causes the former to
not share memory is you are missing a copy=False argument to the
return multi_array(obj, copy=0)
is what you need to use.
Also, the address of the memory is also available as
arr.ctypes.data if arr is a NumPy array (but this is less general than
using the array interface for sure).
More information about the Numpy-discussion