簡體   English   中英

如何使用ctypes將數組從C ++函數返回到Python

[英]How to return array from C++ function to Python using ctypes

我正在使用ctypes在Python中實現C ++函數。 C ++函數應該返回一個指向數組的指針。 不幸的是我還沒弄明白,如何在Python中訪問數組。 我試過numpy.frombuffer,但那不成功。 它只返回了一個任意數字的數組。 顯然我沒有正確使用它。 這是一個大小為10的數組的簡單示例:

function.cpp的內容:

extern "C" int* function(){
int* information = new int[10];
for(int k=0;k<10;k++){
    information[k] = k;
}
return information;
}

wrapper.py的內容:

import ctypes
import numpy as np

output = ctypes.CDLL('./library.so').function()

ArrayType = ctypes.c_double*10
array_pointer = ctypes.cast(output, ctypes.POINTER(ArrayType))
print np.frombuffer(array_pointer.contents)

要編譯我正在使用的C ++文件:

g++ -c -fPIC function.cpp -o function.o
g++ -shared -Wl,-soname,library.so -o library.so function.o

你有什么建議我在Python中訪問數組值嗎?

您的python代碼將在一些小修改后工作:

import ctypes

f = ctypes.CDLL('./library.so').function
f.restype = ctypes.POINTER(ctypes.c_int * 10)
print [i for i in f().contents] # output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

基本上有兩個變化:

  1. 刪除與numpy相關的代碼和ctypes.cast調用,因為我們不需要它們。

  2. 將返回類型指定為ctypes.POINTER(ctypes.c_int * 10)

    默認情況下,假定外部函數返回C int類型,因此我們需要將其更改為所需的指針類型。

BTW,從C代碼返回一個new ed數組到Python代碼似乎不合適。 誰和什么時候會釋放記憶? 最好在Python代碼中創建數組並將它們傳遞給C代碼。 很明顯,Python代碼擁有數組並負責創建和回收它們的空間。

function.cpp返回一個int數組,而wrapper.py嘗試將它們解釋為雙精度數。 ArrayType更改為ctypes.c_int * 10 ,它應該可以工作。


它可能更容易,只需使用np.ctypeslib而不是frombuffer自己。 這看起來應該是這樣的

import ctypes
from numpy.ctypeslib import ndpointer

lib = ctypes.CDLL('./library.so')
lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(10,))

res = lib.function()

暫無
暫無

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

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