在cython中创建2D / 3D C数组

时间:2014-09-16 16:04:47

标签: python arrays cython

有谁能告诉我如何将在cython中创建的2D数组传递给cdef函数?我可以用1D阵列做到这一点,但是 不是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中创建pure-c 2D / 3D数组以及如何将它们传递给c级函数?此外,我试图避免那里的numpy数组,以避免python开销,因为我的代码将需要在数组上非常快速的计算。

1 个答案:

答案 0 :(得分:1)

您需要使输入数组静态:

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