实际上,我正在尝试将 ctypes 数组转换为 python 列表并返回。
如果找到this thread 。但它假设我们在编译时知道类型。
但是是否可以检索元素的 ctypes 类型?
我有一个 python 列表,其中至少包含一个元素。我想做这样的事情
import ctypes
arr = (type(pyarr[0]) * len(pyarr))(*pyarr)
这显然不起作用,因为 type()
不返回 ctypes 兼容类。但即使列表包含直接从 ctypes 创建的对象,上面的代码也不起作用,因为它是该类型的对象实例。
有什么办法可以完成这个任务吗?
[编辑]
好的,这是适合我的代码。我用它来将输入参数从 comtypes 服务器方法转换为 python 列表,并将值返回到数组指针:
def list(count, p_items):
"""Returns a python list for the given times represented by a pointer and the number of items"""
items = []
for i in range(count):
items.append(p_items[i])
return items
def p_list(items):
"""Returns a pointer to a list of items"""
c_items = (type(items[0])*len(items))(*items)
p_items = cast(c_items, POINTER(type(items[0])))
return p_items
如前所述,p_list(items)
需要至少一个元素。
最佳答案
我认为这不可能直接实现,因为多个 ctypes 类型映射到单个 Python 类型。例如 c_int/c_long/c_ulong/c_ulonglong 都映射到 Python int。您会选择哪种类型?您可以创建您的偏好 map :
>>> D = {int:c_int,float:c_double}
>>> pyarr = [1.2,2.4,3.6]
>>> arr = (D[type(pyarr[0])] * len(pyarr))(*pyarr)
>>> arr
<__main__.c_double_Array_3 object at 0x023540D0>
>>> arr[0]
1.2
>>> arr[1]
2.4
>>> arr[2]
3.6
此外,未记录的 _type_
可以告诉 ctypes 数组的类型。
>>> arr._type_
<class 'ctypes.c_double'>
关于python - 如何从 ctypes 数组中获取 ctypes 类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931452/