简体   繁体   中英

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:

>>> np.dot(a,b)
array([ 7, 12])

I translated the code to Cython (as here: http://docs.cython.org/src/tutorial/numpy.html ):

import numpy as np
cimport numpy as np

DTYPE = np.int
ctypedef np.int_t DTYPE_t

def dot(np.ndarray a, np.ndarray b):
    cdef int d = np.dot(a, 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.dot (test.c:1262)
    cdef int d = np.dot(a, 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...

Thanks!

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 = np.dot(a, b)
    return d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM