【发布时间】:2020-09-16 22:30:34
【问题描述】:
我目前正在从 Cython 向 C 传递一个指针的以下指针:
#convert the input Python 2D array to a memory view
cdef double[:,:] a_cython= np.asarray(a,order="C")
#define a pointer of a pointer with dimensions of a
cdef double** point_to_a = <double **>malloc(N * sizeof(double*))
#initialize the pointer
if not point_to_a: raise MemoryError
#try:
for i in range(N):
point_to_a[i] = &a_cython[i, 0]
#pass this double pointer to a C function
logistic_sigmoid(&point_to_a[0], N,M)
其中a 是一个numpy 数组,其维度为N x M,point_to_a 是指向Cython memoryview a_cython 的指针的Cython 指针。由于来自 Python 的输入 a 是二维数组,我认为这是将信息直接传递给 C 的最佳方法。
段落顺利,计算正确完成。但是,我现在正在尝试将 point_to_a 重新转换回 numpy 数组,但我有点挣扎。
我正在考虑各种解决方案。我想探索是否有可能在整个过程中保留一个 N 维数组,因此我在 Cython 中尝试了这种方法:
#define a integer array for dimensions
cdef np.npy_intp dims[2]
dims[0]= N
dims[1] = M
#create a new memory view and PyArray_SimpleNewFromData to deal with the pointer
cdef np.ndarray[double, ndim=2] new_a = np.PyArray_SimpleNewFromData(2, &dims[0], np.NPY_DOUBLE, point_to_a)
但是,当我将 new_a 转换为 np.array 作为 array = np.asarray(new_a) 时,我有一个只有 0 的数组。
你有什么想法吗?
非常感谢
【问题讨论】:
标签: python c arrays numpy cython