如何从C ++函数使用ctypes的返回数组的Python [英] How to return array from C++ function to Python using ctypes

查看:1835
本文介绍了如何从C ++函数使用ctypes的返回数组的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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 试图间preT他们为双打。更改将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.

它可能更容易只使用<一个href=\"http://docs.scipy.org/doc/numpy/reference/routines.ctypeslib.html\"><$c$c>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()

这篇关于如何从C ++函数使用ctypes的返回数组的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆