简体   繁体   English

Python Ctypes:将返回的 C 数组转换为 python 列表,没有 numpy

[英]Python Ctypes: Convert returned C array to python list, WITHOUT numpy

I am using Python Ctypes to access some C library.我正在使用 Python Ctypes 来访问一些 C 库。

One of the functions I connected to, returns const *double , which is actually an array of doubles.我连接的一个函数返回const *double ,它实际上是一个双精度数组。

When I get the result in Python, how can I convert this array to a python list?当我在 Python 中得到结果时,如何将此数组转换为 Python 列表?

The signature of the C function: C函数的签名:

const double *getWeights();

Let's assume that it returns an array that contains 0.13 and 0.12.假设它返回一个包含 0.13 和 0.12 的数组。 I want to get a python List: [0.13, 0.12]我想得到一个 python 列表: [0.13, 0.12]

I succeeded solving it using pointers我成功地使用指针解决了它

The solution:解决方案:

Define the function return type as POINTER(double_c) :将函数返回类型定义为POINTER(double_c)

getWeights_function_handler.restype = POINTER(double_c)

When the function returns, you can use the [] operator to access the C array elements (the same operator used in C):当函数返回时,您可以使用[]运算符访问 C 数组元素(与 C 中使用的运算符相同):

weights = getWeights_function_handler()
mylist = [weights[i] for i in xrange(ARRAY_SIZE_I_KNOW_IN_ADVANCE)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM