[Cython] Automatic buffer dtype conversion?
Dag Sverre Seljebotn
dagss at student.matnat.uio.no
Mon Dec 15 17:57:39 CET 2008
Hei der!
Magnus Lie Hetland wrote:
> Hi!
>
> I've been trying to get the simple Cython+NumPy example from Robert
> Bradshaw's slides to work:
>
>> # footest.pyx
>
>> cimport numpy
>>
>> def sum(x):
>> cdef numpy.ndarray[int, ndim=1] arr = x
>> cdef int i, s = 0
>> for i in range(arr.shape[0]):
>> s += arr[i]
>> return s
>
> I get it to compile/link, but then I try to actually use it, with the
> following code:
>
>> import footest
>> import numpy as np
>>
>> a = np.arange(1000, dtype=np.int)
>> print footest.sum(a)
>
> The np.int shouldn't be necessary -- and I started without it -- but
> even *with* it, I get the following error:
>
>> File "footest.pyx", line 4, in footest.sum (footest.c:392)
>> cdef numpy.ndarray[int, ndim=1] arr = x
>> ValueError: Buffer dtype mismatch (expected int, got long)
Yes, this is very expected on 64-bit systems, I suppose Robert's slides
are in error.
Basically the "np.int" type object is defined (by NumPy) to be long
(probably on merit of being the most convenient int type; read "np.int"
as saying "Integer", not a C int).
To be safe with these things, you should use the compile-time types
defined in the numpy cimport:
cdef numpy.ndarray[numpy.int_t, ndim=1] arr = x
numpy.int_t is typedef-ed to always be whatever np.int refers to.
If you really want a C int, use e.g. numpy.int32(_t).
--
Dag Sverre
More information about the Cython-dev
mailing list