简体   繁体   中英

Calling a Python function from C with Cython: Problems with NumPy data types

So what I'm trying to do is the following:

  1. Call a function in C with either an array or NumPy Array as argument
  2. Do something to the content of the array in Cython / Python, like elementwise multiplication by 2
  3. Return an appropriate data type back to C

My only problem is that I don't know how to create a NumPy Array in C or return an array in my cdef function. I of course have tried googling and reading all over the internet but I simply found nothing really helpful (or didn't understand what was proposed). I tried memoryviews but I didn't get that to work either:

cdef public int[:,:] c_array_to_numpy(int[:,:] input):
    cdef int [:,:] memview = input
    cdef int[2][3] output
    for x in range(memview.shape[0]):
        for y in range(memview.shape[1]):
            memview[x, y] *= 5
            output[x][y] = memview[x][y]
    return output

and in C it should look something like this

int test[2][3] = {{3, 7, 4}, {8, 5, 9}};
c_array_to_numpy(test);
for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 3; j++)
    {
        printf("%i ", test[i][j]);
    }
    printf("\n");
}

Numpy internally uses C arrays, so you do not need to do a conversion.

I'd suggest using scipy.weave first (which allows you to embed C-code in python), and once you have that working, then consider hosting the C-code outside of your python source using an appropriate library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM