我正在使用Python Ctypes访问一些C库。
我连接到的函数之一返回const *double
,实际上是一个双精度浮点数数组。
当我在Python中获取结果时,如何将此数组转换为Python列表?
C函数的签名:
const double *getWeights();
假设它返回一个包含0.13和0.12的数组。我想获得一个Python列表:[0.13, 0.12]
我使用指针成功解决了它
解决方案:
将函数返回类型定义为POINTER(double_c)
:
getWeights_function_handler.restype = POINTER(double_c)
当函数返回时,你可以使用[]
操作符来访问C数组元素(与C中使用的相同操作符):
weights = getWeights_function_handler()
mylist = [weights[i] for i in xrange(ARRAY_SIZE_I_KNOW_IN_ADVANCE)]
int array_length = sizeof(array) / sizeof(double);
,假设这个数组是double[]
类型的。 - SomethingSomethingint*
C 函数参数,其中数组长度将由 C 函数编写,以便在函数返回时可以在 Python 中知道它。使用 ctypes.byref()
或 ctypes.pointer()
从 Python 传递这样的参数到 C 应该是可行的。请参阅此处的答案:https://dev59.com/u1vUa4cB1Zd3GeqPupHW - SomethingSomethingctypes.byref()
和ctypes.pointer()
的区别,请参考此线程:https://dev59.com/Ymct5IYBdhLWcg3wLqnw - SomethingSomething
result
是您的C函数的返回值,如果在Python中执行print(type(result))
或print(repr(result))
会发生什么? - Henry Keitersome_constant
- SomethingSomethingc_double_Array_2
。 - SomethingSomethingtype
还是repr
?在print(repr(result))
的结果中是否包含内存地址?如果repr
看起来不像'<c_double_Array_2 object at 0.0000000002B6EE48>'
,那么你看到的是类型而不是实际实例。 - Henry Keiter