[Numpy-discussion] Re: copying ctypes arrays to numarray?

Florian Schulze florian.proff.schulze at gmx.net
Thu Dec 16 01:15:02 CST 2004


On Wed, 15 Dec 2004 20:16:07 -0800, RJ <rays at san.rr.com> wrote:

> I'm posting here to see if numarray has a method that could work like 
> array.buffer_info().  numarray.info() returns a text output that can't 
> be used like the array method is to memmove() between ctypes and Python 
> arrays without parsing, apparently.
>
> ctypes thread with Thomas Heller below. His main question: "Maybe you 
> should ask to make sure that there's no way to copy between
> objects implementing the buffer protocol with some Python function that
> I do not know about?"

I just tried some things:
>>> import ctypes
>>> a = (ctypes.c_int * 5)()
>>> a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5
>>> list(a)
[1, 2, 3, 4, 5]
>>> import numarray

>>> buf = numarray.zeros(shape=20, type='i4')
>>> buf
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> buf[2:7] = a
>>> buf
array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

>>> temp = numarray.array(sequence=buffer(a), shape=5, type='i4')
>>> temp
array([1, 2, 3, 4, 5])
>>> temp._data
<read-only buffer for 0x00FA9230, ptr 0x00BFA668, size 20 at 0x010D6DA0>
>>> buffer(a)
<read-only buffer for 0x00FA9230, ptr 0x00BFA668, size 20 at 0x00FAF600>

>>> a[2] = 10
>>> temp
array([ 1,  2, 10,  4,  5])

The first block just creates the ctypes data.

The second block uses slice assignment to copy the data from the ctypes 
array into the numarray.array.

The third block uses the buffer interface to create a numarray.array which 
points to the same memory location as the ctypes array.

The forth block illustrates that it's really the same memory.

You have to benchmark which one of the two solutions is the better one for 
you.

Regards,
Florian Schulze





More information about the Numpy-discussion mailing list