Pass a 2d numpy array to c using ctypes

前端 未结 3 1081
天涯浪人
天涯浪人 2020-12-13 22:45

What is the correct way to pass a numpy 2d - array to a c function using ctypes ? My current approach so far (leads to a segfault):

C code :

void te         


        
3条回答
  •  醉话见心
    2020-12-13 23:03

    #include 
    
    void test(double (*in_array)[3], int N){
        int i, j;
    
        for(i = 0; i < N; i++){
            for(j = 0; j < N; j++){
                printf("%e \t", in_array[i][j]);
            }
            printf("\n");
        }
    }
    
    int main(void)
    {
        double a[][3] = {
            {1., 2., 3.},
            {4., 5., 6.},
            {7., 8., 9.},
        };
    
        test(a, 3);
        return 0;
    }
    

    if you want to use a double ** in your function, you must pass an array of pointer to double (not a 2d array):

    #include 
    
    void test(double **in_array, int N){
        int i, j;
    
        for(i = 0; i < N; i++){
            for(j = 0; j< N; j++){
                printf("%e \t", in_array[i][j]);
            }
            printf("\n");
        }
    }
    
    int main(void)
    {
        double a[][3] = {
            {1., 2., 3.},
            {4., 5., 6.},
            {7., 8., 9.},
        };
        double *p[] = {a[0], a[1], a[2]};
    
        test(p, 3);
        return 0;
    }
    

    Another (as suggested by @eryksun): pass a single pointer and do some arithmetic to get the index:

    #include 
    
    void test(double *in_array, int N){
        int i, j;
    
        for(i = 0; i < N; i++){
            for(j = 0; j< N; j++){
                printf("%e \t", in_array[i * N + j]);
            }
            printf("\n");
        }
    }
    
    int main(void)
    {
        double a[][3] = {
            {1., 2., 3.},
            {4., 5., 6.},
            {7., 8., 9.},
        };
    
        test(a[0], 3);
        return 0;
    }
    

提交回复
热议问题