Cython: buffer type mismatch expected by 'int' but receiving 'long'

I am having trouble passing integers in this memory to this (rather trivial) function. Python gives me this error:

ValueError: Buffer dtype mismatch, expected 'int' but got 'long' 

Can someone help me understand what is happening? Searching around stackoverflow, it seems to be related to how python interprets types and how C interprets types.

 %%cython def myfunction(int [:] y): pass # Python code import numpy as np y = np.array([0, 0, 1, 1]) myfunction(y) 

This creates a ValueError on top.

EDIT: Here are some other things that I discovered.

To clarify, this error persists if I declare y following ways:

 y = np.array([0, 0, 1, 1], dtype='int') y = np.array([0, 0, 1, 1], dtype=np.int) y = np.array([0, 0, 1, 1], dtype=np.int64) 

However, it works if I declare y with

 y = np.array([0, 0, 1, 1], dtype=np.int32) 

Anyone want to give a suggestion why this is so? Will throwing np.int32 work on different computers? (I am using macbook pro retina, 2013.)

+7
python numpy cython memoryview
source share
3 answers

You are using the Cython int type, which is just C int . I think on a Mac (or on most architectures) it is 32-bit. See wiki or intel or Does int size depend on compiler and / or processor?

On the other hand, long means int64. dtype='int' or dtype=np.int equivalent to np.int64 .

I think you can just explicitly define it as one of the numpy types:

 cimport numpy as np import numpy as np cdef myfunction(np.ndarray[np.int64_t, ndim=1] y): #do something pass 

Thus, it is read more clearly, and later there will be no confusion.

EDIT

The new memoryviews syntax will look like this:

 cdef myfunction(double[:] y): #do something with y pass 
+9
source share

I did what the error message told me: I changed the base type of memoryview from int to long and it seemed to work.

 %%cython def fun(long[:] x): return x[0] y=np.array([1,2,3],dtype=int) fun(y) # returns 1 
0
source share

I had the same problem. Yibo's motivated answer, I used .astype (int), which solved the problem.

0
source share

All Articles