簡體   English   中英

使用 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 列表?

您返回的指針實際上與您傳遞的指針相同。 即您實際上並不需要返回數組指針。

您將指向支持列表的內存區域的指針從 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM