[Numpy-discussion] Ctypes support in NumPy

Albert Strasheim fullung at gmail.com
Mon Jul 3 04:11:21 EDT 2006


Hello all

Travis Oliphant wrote:
> <snip>
> Unfortunately, from the source code this is not true.  It would be an
> improvement, but the source code shows that the from_param of each type
> does something special and only works with particular kinds of
> data-types --- basic Python types or ctypes types.  I did not see
> evidence that the _as_parameter_ method was called within any of the
> from_param methods of _ctypes.c

To summarise, I think we've come to the conclusion that one should avoid
argtypes when mixing NumPy with ctypes? (at least for now)

The extensions to .ctypes you propose below should make it possible to use
NumPy arrays with argtypes set. "Raw" C functions will probably be wrapped
by a Python function 99.9% of the time for error checking, etc. This hides
the need to call the .ctypes stuff from the user.

> <snip>

> > Maybe there should be a way to get a pointer to the NumPy array data as
> a
> > POINTER(c_double) if it is known that the array's dtype is float64.
> Ditto
> > for c_int/int32 and the others.
> >
> 
> I could see value in
> 
> arr.ctypes.data_as()
> arr.ctypes.strides_as()
> arr.ctypes.shape_as()
> 
> methods which allow returning the data as different kinds of c-types
> things instead of the defaults --- Perhaps we just make data, strides,
> and shapes methods with an optional argument.

Agreed. If you really like argtypes, arr.ctypes.data_as() would be perfect
for doing the necessary work to make sure ctypes accepts the array.
arr.ctypes.data_as(c_type) could be implemented as 

ctypes.cast(x.ctypes.data, ctypes.POINTER(c_type))

c_void_p, c_char_p and c_wchar_p are special cases that aren't going to work
here, so maybe it should be

ctypes.cast(x.ctypes.data, c_type)

in which case one mostly call it as arr.ctypes.data_as(POINTER(c_type)).

Regards,

Albert





More information about the NumPy-Discussion mailing list