【问题标题】:Returning a C array from a C function to Python using ctypes使用 ctypes 将 C 数组从 C 函数返回到 Python
【发布时间】:2019-01-21 06:52:35
【问题描述】:

我目前正在尝试通过编写一个 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 列表?

【问题讨论】:

标签: python c ctypes


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢!它现在对我有用。还有一件事......我如何构造一个 2d ctypes 数组?干杯,尼克
猜你喜欢
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2021-06-08
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多