谁能启发我如何将cython中创建的2D数组传递给cdef函数?我可以用一维数组来做到这一点,但是
而不是2D(或更高),让我说明一下这种情况:

这是我想在cython中重现的C代码:

#include <stdio.h>

void print_my_1Darray();
void print_my_2Darray();

int main(void){

    int arr1D[] = {1,2,3,4,5,6,7,8,9,10,11,12};
    int arr2D[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

    print_my_1Darray(arr1D);
    printf("\n");
    print_my_2Darray(arr2D);
    printf("\n");
    return 0;
}

void print_my_1Darray( int x[] ){

    int i;
    for(i=0; i < 12; i++){
        printf("c[%d] = %d\n",i, x[i]);
    }
}

void print_my_2Darray( int x[3][4] ){

    int i, j;
    for(i=0; i < 3; i++){
        for(j=0; j < 4; j++){
        printf("c[%d][%d] = %d\n",j, i, x[i][j]);
        }
    }
}


然后,如果我尝试像这样在Cython中重现此内容:

cimport cython
import numpy as np
cimport numpy as cnp

def testfunc():

    cdef int *arr1D = [1,2,3,4,5,6,7,8,9,10,11,12]
    print_my_1D_array(arr1D)

    cdef int *arr2D = [[1,2,3,4][5,6,7,8][9,10,11,12]]   # <-- WRONG!
    print_my_2D_array(arr2D)


cdef void print_my_1D_array(int c_arr[12] ):

    cdef int i

    for i in range(4):
    print c_arr[i]

cdef void print_my_2D_array(int c_arr[3][4] ):

    cdef int i, j

    for i in range(3):
    for j in range(4):
        print c_arr[i][j]


当我编译这个pyx脚本时,出现错误:

    cdef int *arr2D = [[1,2,3,4][5,6,7,8][9,10,11,12]]
    print_my_2D_array(arr2D)
                      ^
    ------------------------------------------------------------

    test2.pyx:18:27: Cannot assign type 'int *' to 'int (*)[4]'


看来我可以用

  "cdef int *arr2D = [[1,2,3,4][5,6,7,8][9,10,11,12]]"


行,它会编译确定,直到我尝试将其传递给函数或仅打印其成员为止。

谁能解释那里发生了什么以及如何在cython中创建纯c 2D / 3D数组以及如何将它们传递给c级函数?另外,我正在尝试避免在那里使用numpy数组以避免python开销,因为我的代码将需要对数组进行非常快速的计算。

最佳答案

您需要将输入数组设为静态:

cdef int arr2D[3][4]
arr2D[0][:] = [1,  2,  3,  4]
arr2D[1][:] = [5,  6,  7,  8]
arr2D[2][:] = [9, 10, 11, 12]

09-16 06:11