[Numpy-discussion] numpy.ctypeslib.ndpointer and the restype attribute [patch]
Thomas Heller
theller at ctypes.org
Thu Mar 26 16:12:00 EDT 2009
Sturla Molden schrieb:
> On 3/26/2009 12:41 PM, Jens Rantil wrote:
>
>> Wouldn't my code, or a tweak of it, be a nice feature in
>> numpy.ctypeslib? Is this the wrong channel for proposing things like
>> this?
>
> If you look at
>
> http://svn.scipy.org/svn/numpy/trunk/numpy/ctypeslib.py
>
> you will see that it does almost the same. I think it would be better to
> work out why ndpointer fails as restype and patch that.
ndpointer(...), which returns an _nptr instance, does not work as restype
because neither it is a base class of one of the ctypes base types like
ctypes.c_void_p, also it is not callable with one argument.
There are two ways to fix this. The first one is to make the _nptr callable
with one argument, by implementing a method like this:
def __init__(self, anInteger):
The foreign function is assumed to return an integer, and the restype
is called with this integer. Obviously this will only work on systems
where 'sizeof(int) == sizeof(void *)'. See also
http://docs.python.org/library/ctypes.html#return-types
I consider the 'callable as restype' protocol broken, but backwards
compatibility reasons forbid to change that.
The other way is to make _nptr a subclass of ctypes.c_void_p,
the result that the foreign function call returns will then be
an instance of this class. Unfortunately, ctypes will not call
__new__() to create this instance; so a custom __new__() implementation
cannot return a numpy array and we are left with the _nptr instance.
The only way to create and access the numpy array is to construct
and return one from a method call on the _nptr instance, or a property
on the _nptr instance.
Ok, .errcheck could call that method and return the result.
--
Thanks,
Thomas
More information about the NumPy-Discussion
mailing list