Passing numpy array to Cython

I am learning Cython. I have problem with passing numpy arrays to Cython and don’t really understand what is going on. Could you help me?

I have two simple arrays:

a = np.array([1,2])
b = np.array([[1,4],[3,4]])

I want to compute a dot product of them. In python/numpy everything works fine:

array([ 7, 12])

I translated the code to Cython (as here:

import numpy as np
cimport numpy as np

ctypedef np.int_t DTYPE_t

def dot(np.ndarray a, np.ndarray b):
    cdef int d =, b)
    return d

It compiled with no problems but returns an error:

>>> dot(a,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.pyx", line 8, in (test.c:1262)
    cdef int d =, b)
TypeError: only length-1 arrays can be converted to Python scalars

Could you tell me why and how to do it correctly? Unfortunately Google was not helpful…


Best answer

Your result is np.ndarray, not int. It fails trying to convert first one to latter. Do instead

def dot(np.ndarray a, np.ndarray b):
    cdef np.ndarray d =, b)
    return d