如何使用ctypes将数组从C ++函数返回到Python
我正在使用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中访问数组值有什么建议?
-
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()