在Cython和NumPy中包装C函数

Pet*_*ter 10 c python numpy cython word-wrap

我想从Python调用我的C函数,以便操作一些NumPy数组.功能是这样的:

void c_func(int *in_array, int n, int *out_array);
Run Code Online (Sandbox Code Playgroud)

结果在out_array中提供,其大小我事先知道(实际上不是我的函数).我尝试在相应的.pyx文件中执行以下操作,以便能够将输入从NumPy数组传递给函数,并将结果存储在NumPy数组中:

def pyfunc(np.ndarray[np.int32_t, ndim=1] in_array):    
    n = len(in_array)
    out_array = np.zeros((512,), dtype = np.int32)
    mymodule.c_func(<int *> in_array.data, n, <int *> out_array.data)
    return out_array
Run Code Online (Sandbox Code Playgroud)

但我得到 "Python objects cannot be cast to pointers of primitive types"输出分配的错误.我该如何做到这一点?

(如果我要求Python调用者分配正确的输出数组,那么我可以这样做

def pyfunc(np.ndarray[np.int32_t, ndim=1] in_array, np.ndarray[np.int32_t, ndim=1] out_array):  
    n = len(in_array)
    mymodule.cfunc(<int *> in_array.data, n, <int*> out_array.data)
Run Code Online (Sandbox Code Playgroud)

但是我可以这样做,调用者不必预先分配适当大小的输出数组吗?

Sim*_*got 5

您应该cdef np.ndarrayout_array分配之前添加:

def pyfunc(np.ndarray[np.int32_t, ndim=1] in_array):    
    cdef np.ndarray out_array = np.zeros((512,), dtype = np.int32)
    n = len(in_array)
    mymodule.c_func(<int *> in_array.data, n, <int *> out_array.data)
    return out_array
Run Code Online (Sandbox Code Playgroud)