【问题标题】:Calling a Python function from C with Cython: Problems with NumPy data types使用 Cython 从 C 调用 Python 函数:NumPy 数据类型的问题
【发布时间】:2020-04-14 14:28:07
【问题描述】:

所以我想做的是以下几点:

  1. 使用数组或 NumPy 数组作为参数调用 C 中的函数
  2. 在 Cython / Python 中对数组的内容做一些事情,比如元素乘以 2
  3. 将适当的数据类型返回给 C

我唯一的问题是我不知道如何在 C 中创建一个 NumPy 数组或在我的 cdef 函数中返回一个数组。我当然尝试过在互联网上搜索和阅读,但我发现没有任何真正有用的东西(或者不明白建议的内容)。我尝试了 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

在 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");
}

【问题讨论】:

    标签: python c arrays numpy cython


    【解决方案1】:

    Numpy 内部使用 C 数组,因此您无需进行转换。

    我建议首先使用 scipy.weave(它允许您在 python 中嵌入 C 代码),一旦您可以使用,然后考虑使用适当的库在您的 python 源之外托管 C 代码。

    【讨论】:

      猜你喜欢
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 2012-03-17
      相关资源
      最近更新 更多