在cython中定义c函数返回numpy数组

man*_*ius 7 numpy cython

我不确定以下问题是否有意义,因为我是新手.我试图在Cython中创建一个C函数,它返回一个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
Run Code Online (Sandbox Code Playgroud)

但是,不要让我编译它.但是,如果我删除函数的返回类型

cdef SumPlusOne(np.ndarray[np.int32_t, ndim=1] ArgArray):
    ...
Run Code Online (Sandbox Code Playgroud)

没有问题.

我的问题是,有没有办法为返回值声明numpy类型?我真的不知道这是否可行,因为我不知道np.ndarray是否需要转换为python类型.

谢谢

hpa*_*ulj 7

根据cython文档,对于一个cdef功能:

如果没有为参数或返回值指定类型,则假定它是Python对象.

A numpy array是一个Python对象.不需要转换为Python"类型".它的元素可能是Python/C类型(dtype),但数组作为一个整体是一个对象.

np.zeros((len(ArgArray), dtype = np.int32)
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)