问题描述
我正在使用 ctypes 在 Python 中实现 C++ 函数.C++ 函数应该返回一个指向数组的指针.不幸的是,我还没有弄清楚,如何在 Python 中访问数组.我试过 numpy.frombuffer,但没有成功.它只是返回一个任意数字的数组.显然我没有正确使用它.这是一个大小为 10 的数组的简单示例:
I am using ctypes to implement a C++ function in Python. The C++ function should return a pointer to an array. Unfortunately I haven't figured out, how to access the array in Python. I tried numpy.frombuffer, but that was not successful. It just returned an array of arbitrary numbers. Obviously I didn't used it correctly. Here is a simple example with an array of size 10:
function.cpp 的内容:
Content of 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 的内容:
Content of 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++ 文件:
To compile the C++ file i am using:
g++ -c -fPIC function.cpp -o function.o
g++ -shared -Wl,-soname,library.so -o library.so function.o
你对我在 Python 中访问数组值必须做什么有什么建议吗?
Do you have any suggestions what I have to do to access the array values in Python?
推荐答案
function.cpp
返回一个 int 数组,而 wrapper.py
尝试将它们解释为双精度数组.将 ArrayType
更改为 ctypes.c_int * 10
就可以了.
function.cpp
returns an int array, while wrapper.py
tries to interpret them as doubles. Change ArrayType
to ctypes.c_int * 10
and it should work.
使用 np.ctypeslib
而不是 frombuffer
自己.这应该看起来像
It's probably easier to just use np.ctypeslib
instead of frombuffer
yourself. This should look something like
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()
这篇关于如何使用 ctypes 将数组从 C++ 函数返回到 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!