return cython定义的c函数中的numpy数组
return numpy array in cython defined c function
由于我是新手,所以我不确定以下问题是否有意义。
我正在尝试在 Cython 中创建一个 C 函数,它 return 是一个 numpy 数组,如下所示。
cdef np.ndarray[np.int32_t, ndim=1] SumPlusOne(np.ndarray[np.int32_t, ndim=1] ArgArray):
cdef np.ndarray[int32_t, ndim=1] ReturnArray = np.zeros((len(ArgArray), dtype = np.int32)
ReturnArray = ArgArray + 1
return ReturnArray
但是,就是不让我编译。但是如果我删除函数的 return 类型
cdef SumPlusOne(np.ndarray[np.int32_t, ndim=1] ArgArray):
...
没有问题。
我的问题是,有什么方法可以为 return 值声明 numpy 类型吗?我真的不知道这是否可能,因为我不知道 np.ndarray 是否需要转换为 python 类型。
谢谢
根据 cython
文档,对于 cdef
函数:
If no type is specified for a parameter or return value, it is assumed to be a Python object.
一个numpy array
是一个Python对象。不需要转换为 Python 'type'。它的元素可能是 Python/C 类型(dtype),但整个数组是一个对象。
np.zeros((len(ArgArray), dtype = np.int32)
在 Python 中的工作与在 Cython 中一样好。
在我的有限测试中,您的两个 cdef 都有效。也许是 cython
版本的问题?
这在 cpdef
之后有和没有类型声明都有效(使用这种形式所以我可以从 Python 调用它)
import numpy as np
cimport numpy as np
cimport cython
cpdef np.ndarray[np.int32_t, ndim=1] sum_plus_one(np.ndarray[np.int32_t, ndim=1] arg):
cdef np.ndarray[np.int32_t, ndim=1] result = np.zeros((len(arg)), dtype = np.int32)
result = arg + 1
return result
由于我是新手,所以我不确定以下问题是否有意义。 我正在尝试在 Cython 中创建一个 C 函数,它 return 是一个 numpy 数组,如下所示。
cdef np.ndarray[np.int32_t, ndim=1] SumPlusOne(np.ndarray[np.int32_t, ndim=1] ArgArray):
cdef np.ndarray[int32_t, ndim=1] ReturnArray = np.zeros((len(ArgArray), dtype = np.int32)
ReturnArray = ArgArray + 1
return ReturnArray
但是,就是不让我编译。但是如果我删除函数的 return 类型
cdef SumPlusOne(np.ndarray[np.int32_t, ndim=1] ArgArray):
...
没有问题。
我的问题是,有什么方法可以为 return 值声明 numpy 类型吗?我真的不知道这是否可能,因为我不知道 np.ndarray 是否需要转换为 python 类型。
谢谢
根据 cython
文档,对于 cdef
函数:
If no type is specified for a parameter or return value, it is assumed to be a Python object.
一个numpy array
是一个Python对象。不需要转换为 Python 'type'。它的元素可能是 Python/C 类型(dtype),但整个数组是一个对象。
np.zeros((len(ArgArray), dtype = np.int32)
在 Python 中的工作与在 Cython 中一样好。
在我的有限测试中,您的两个 cdef 都有效。也许是 cython
版本的问题?
这在 cpdef
之后有和没有类型声明都有效(使用这种形式所以我可以从 Python 调用它)
import numpy as np
cimport numpy as np
cimport cython
cpdef np.ndarray[np.int32_t, ndim=1] sum_plus_one(np.ndarray[np.int32_t, ndim=1] arg):
cdef np.ndarray[np.int32_t, ndim=1] result = np.zeros((len(arg)), dtype = np.int32)
result = arg + 1
return result