简体   繁体   English

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

[英]Returning a C array from a C function to Python using ctypes

I'm currently trying to reduce the run time of Python program by writing a C function to do the heavy lifting on a very large array.我目前正试图通过编写一个 C 函数来完成一个非常大的数组的繁重工作,以减少 Python 程序的运行时间。 At the moment I'm just working with this simple function.目前我只是在使用这个简单的功能。

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

All I want my Python code to do is call the C function and then have the new array returned.我想让我的 Python 代码做的就是调用 C 函数,然后返回新数组。 Here's what I have so far:这是我到目前为止所拥有的:

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

How do I create a Python list from the returned pointer?如何从返回的指针创建 Python 列表?

The pointer you're returning is actually the same that you're passing.您返回的指针实际上与您传递的指针相同。 Ie you don't actually need to return the array pointer.即您实际上并不需要返回数组指针。

You are handing over a pointer to the memory area backing the list from Python to C, the C function can then change that memory.您将指向支持列表的内存区域的指针从 Python 移交给 C,然后 C 函数可以更改该内存。 Instead of returning the pointer, you can return an integer status code to flag whether everything went as expected.您可以返回一个整数状态代码来标记是否一切都按预期进行,而不是返回指针。

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.
}

From the Python side, you can view the results by inspecting arr.在 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

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

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