使用 ctypes 将 C 数组从 C 函数返回到 Python

Returning a C array from a C function to Python using ctypes

我目前正在尝试通过编写一个 C 函数来对一个非常大的数组执行繁重的工作,从而减少 Python 程序的 运行 时间。目前我正在使用这个简单的函数。

int * addOne(int array[4])
{
    int i;
    for(i = 0; i < 5; i++)
    {
        array[i] = array[i] + 1;
    }
    return array;
}

我想要我的 Python 代码做的就是调用 C 函数,然后返回新数组。这是我目前所拥有的:

from ctypes import *
libCalc = CDLL("libcalci.so")
pyarr = [65, 66, 67, 68]
arr = (ctypes.c_int * len(pyarr))(*pyarr)
res = libCalc.addOne(arr)

如何根据返回的指针创建 Python 列表?

您 return 指向的指针实际上与您传递的指针相同。 IE。您实际上不需要 return 数组指针。

您正在将一个指向支持列表的内存区域的指针从 Python 移交给 C,然后 C 函数可以更改该内存。您可以 return 一个整数状态代码来标记一切是否按预期进行,而不是 returning 指针。

int addOne(int array[4])
{
    int i;
    for(i = 0; i < 5; i++)
    {
        array[i] = array[i] + 1; //This modifies the underlying memory
    }
    return 0; //Return 0 for OK, 1 for problem.
}

从 Python 端,您可以通过检查 arr 查看结果。

from ctypes import *
libCalc = CDLL("libcalci.so")
pyarr = [65, 66, 67, 68]                   #Create List with underlying memory
arr = (ctypes.c_int * len(pyarr))(*pyarr)  #Create ctypes pointer to underlying memory
res = libCalc.addOne(arr)                  #Hands over pointer to underlying memory

if res==0:
    print(', '.join(arr))                  #Output array