[Numpy-discussion] Numpy array from ctypes pointer object?

Mark Heslep mark at mitre.org
Wed Jul 12 12:42:44 CDT 2006

I don't see a clean way to create a numpy array from a ctypes pointer object. Is the __array_interface_ in ctypes the thing thats missing needed to make this happen?  I've followed Albert's  Scipy cookbook on ctypes here

http://www.scipy.org/Cookbook/Ctypes  <-- getting dated now for numpy SVN but the idea is clear

This shows clean ways to
1) Create a ctype array object from a numpy array:
    npptr= nparray.__array_interface__['data'][0]
    ctarray = (c_double * nparray.size).from_address(npptr)

2) Create a numpy array from a ctypes array (not a pointer):
    ctarray = (c_double * 2)()
    nparray = N.array( ctarray )

But if  I'm starting with say, a POINTER(c_int) and a separate size argument that's returned from a ctypes foreign function or provided by _fields_ element in a ctypes structure, then I'm unclear how to provide the pointer in Python to numpy.  The numpy methods or creating an array in Python as I see it are basically two:

N.array, N.asarray  <-- require a sequence object
N.fromstring, N.frombuffer  <-- not available unless given c_char_p and even thats wrong if I don't want zero termination.

The attributes in nparray.__array_interface_ are not writable, so no joy there.

On the C side the PyArray_SimpleNewFromData( ..dimensions, ...data ptr) C API does the job nicely.  Is there a ctypes paradigm for SimpleNew...?


More information about the Numpy-discussion mailing list