如何使用Cython处理从C函数返回的2D数组? [英] How to work with 2D array returned from c function using Cython?

查看:125
本文介绍了如何使用Cython处理从C函数返回的2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地使用Cython将numpy数组发送到c函数。每当我在c中使用 int * 的函数并且在python中有一些变量时,将其称为 arr ,是一维numpy数组,我只需使用& arr [0] 调用该函数即可。

I have had success in sending numpy arrays to c functions with Cython. Whenever I have a function in c that takes int * and I have some variable in python, call itarr, that is 1D numpy array I just call the function with &arr[0] and it works.

现在,我有兴趣接收使用c函数创建的2D数组。我怎样才能做到这一点?以下是我尝试过的操作。

Now I'm interested in receiving a 2D array created with a c function. How can I do this? Below is what I've tried.

// this is the c code that returns a 2D array
int **make_array() {
  int nrows = 3;
  int ncols = 5;

  int **ret = malloc(nrows * sizeof(int *));
  ret[0] = calloc(nrows * ncols, sizeof(int));
  for (int i = 1; i < nrows; i++) {
    ret[i] = ret[0] + i * ncols;
  }

  int count = 0;
  for (int i = 0; i < nrows; i++)
    for (int j = 0; j < ncols; j++)
      ret[i][j] = ++count;

  return ret;
}

python代码

# python code that receives the 2D array
def foo():
    cdef int nRows = 3
    cdef int nCols = 5
    cdef int[:,::1] ret = np.zeros((nRows, nCols), dtype=np.int32)
    ret = make_array()

对于函数的最后一行,这给了我以下错误:

This gives me the following error for the last line of the function:

Cannot convert 'int **' to memoryviewslice

如果我不创建memoryview而是在接收输出的调用点创建一些变量,对该变量的赋值将正常进行。问题是我仍然不知道如何使用返回值。例如,我无法执行以下操作:

If I don't create a memoryview and instead have some variable created at the point of the call to receive the output the assignment to the variable will work fine. The problem is that I still can't figure out how to work with the returned value. For example I can't do this:

# python code that receives the 2D array
def foo():
    cdef int nRows = 3
    cdef int nCols = 5
    ret = make_array() # works
    print(ret) # fails

它有同样的错误:

Cannot convert 'int **' to Python object

如何使用 int ** 是从ac函数返回的吗?

How can one work with int ** returned from a c function?

推荐答案

由于python无法从C语言转换指针程序,我建议您在C代码中使用 struct ,然后按如下所示的值返回 struct : -

As python is not capable of converting pointers from a C program I would rather advise you to use struct in your C code and then just return the struct by value like below:-

struct TDArray {
    int arr[3][3];
};

struct TDArray make_array() {
    struct TDArray numbers = {
        {
            {0, 1, 2},
            {3, 4, 5},
            {6, 7, 8}
        }
    };//I am hard coding it you just need utilize this approach in your code
            /* Something like
            struct TDArray numbers;
            numbers.arr[0][0]=0;
           */

    return numbers;
}

希望这对您有帮助。

这篇关于如何使用Cython处理从C函数返回的2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆