Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Cython和NumPy中包装C函数_Python_C_Numpy_Cython_Word Wrap - Fatal编程技术网

Python 在Cython和NumPy中包装C函数

Python 在Cython和NumPy中包装C函数,python,c,numpy,cython,word-wrap,Python,C,Numpy,Cython,Word Wrap,我想从Python中调用我的C函数,以便操作一些NumPy数组。功能如下: void c_func(int *in_array, int n, int *out_array); 结果以out_数组的形式提供,我事先知道它的大小(实际上不是我的函数)。我尝试在相应的.pyx文件中执行以下操作,以便能够将输入从NumPy数组传递到函数,并将结果存储到NumPy数组中: def pyfunc(np.ndarray[np.int32_t, ndim=1] in_array): n =

我想从Python中调用我的C函数,以便操作一些NumPy数组。功能如下:

void c_func(int *in_array, int n, int *out_array);
结果以out_数组的形式提供,我事先知道它的大小(实际上不是我的函数)。我尝试在相应的.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

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

下面是一个如何使用C/C++编写的代码通过ctypes操作NumPy数组的示例。 我用C编写了一个小函数,从第一个数组中取数字的平方,然后将结果写入第二个数组。元素的数量由第三个参数给出。此代码编译为共享对象

squares.c编译为squares.so:

void square(double* pin, double* pout, int n) {
    for (int i=0; i<n; ++i) {
        pout[i] = pin[i] * pin[i];
    }
}

这适用于任何c库,您只需知道要传递哪些参数类型,可能需要使用ctypes在python中重建c结构。

您应该在
out\u数组
赋值之前添加
cdef np.ndarray

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
def pyfunc(数组中的np.ndarray[np.int32,ndim=1]:
cdef np.ndarray out_数组=np.zeros((512,),dtype=np.int32)
n=len(在数组中)
mymodule.c_func(in_array.data,n,out_array.data)
返回输出数组

我认为OP希望使用cython而不是ctypesdid您是否尝试在
out\u array
赋值之前提供add
cdef np.ndarray
import numpy as np
import ctypes

n = 5
a = np.arange(n, dtype=np.double)
b = np.zeros(n, dtype=np.double)

square = ctypes.cdll.LoadLibrary("./square.so")

aptr = a.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
bptr = b.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
square.square(aptr, bptr, n)

print b
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