以下线程中的答案对我没有帮助,因为我有多维数组 Passing memoryview to C function .
我有以下测试代码:
头文件:
//cm.h
double per(double **marr,int rows,int cols);
带有 C 函数的文件
//cm.c
#include <stdio.h>
double per(double **marr,int rows,int cols){
int i,j;
for (i=0;i<rows;i++){
for (j=0;j<cols;j++){
//Just update the array
marr[i][j] = (double)(i+1)*(j+1);
}
}
}
Cython 文件:
#m.pyz
import numpy as np
cimport numpy as np
from cython.view cimport array as cvarray
cdef extern from 'cm.h':
double per(double **marr,int rows,int cols);
def test(double[:,::1] x):
cdef int rows = x.shape[0]
cdef int cols = x.shape[1]
per(x,rows,cols)
for i in range(rows):
for j in range(cols):
print x[i,j]
和错误信息:
Error compiling Cython file:
------------------------------------------------------------
...
double per(double **marr,int rows,int cols);
def test(double[:,::1] x):
cdef int rows = x.shape[0]
cdef int cols = x.shape[1]
per(x,rows,cols)
^
------------------------------------------------------------
m.pyx:12:9: Cannot assign type 'double[:, ::1]' to 'double **'
我读过类型化内存 View 是在 Cython 中处理 Python 数组的最现代方式,但我不知道如何执行此操作。我在 C 中有一些数值配方,它们对动态生成的大型多维数组进行操作。
我尝试做的是完全错误的方式吗?
最佳答案
在内部,内存 View 实际上存储为一维数组以及一些有关维度大小的信息。见 http://docs.cython.org/src/userguide/memoryviews.html#brief-recap-on-c-fortran-and-strided-memory-layouts
(作为一个轻微的旁注,您可以拥有具有“间接”维度的内存 View ,它们确实将事物存储为指向指针的指针。这仅在它们是已经像这样分配内存的事物的 View 时才有意义 - 例如,如果您构建一个像 C 中那样的 2D 数组。你不会从(比如)numpy 对象中得到那些,所以我会忽略这个细节)。
您将 C 更改为
// pass a 1D array, and then calculate where we should be looking in it
// based on the stride
double per(double *marr,int rows,int cols, int row_stride, int col_stride){
int i,j;
for (i=0;i<rows;i++){
for (j=0;j<cols;j++){
//Just update the array
marr[row_stride*i + col_stride*j] = (double)(i+1)(j+1);
}
}
}
然后 Cython 代码需要更改以将步长(以字节存储,因此除以 itemsize 以获得 C 期望的“ double 数”中的步长)以及第一个元素的地址
// also update the cdef defintion for per...
per(&x[0,0],x.shape[0],x.shape[1],
x.strides[0]/x.itemsize,x.strides[1]/x.itemsize)
关于multidimensional-array - 将多维内存 View 传递给 c 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34592961/