简体   繁体   English

使用 Cython 从 C 调用 Python function:Z3B7F7949B2346EF5E1E7F 数据类型的问题

[英]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使用数组或 NumPy 数组作为参数调用 C 中的 function
  2. Do something to the content of the array in Cython / Python, like elementwise multiplication by 2对 Cython / Python 中的数组内容做一些事情,比如元素乘以 2
  3. Return an appropriate data type back to C将适当的数据类型返回给 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.我唯一的问题是我不知道如何在 C 中创建一个 NumPy 数组或在我的 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:我尝试了 memoryviews 但我也没有让它工作:

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在 C 中它应该看起来像这样

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. Numpy内部使用C arrays,所以不需要做转换。

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.我建议首先使用 scipy.weave (它允许你在 python 中嵌入 C 代码),一旦你有这个工作,然后考虑使用适当的库在你的 python 源之外托管 C 代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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