实际上,我正在尝试将ctype数组转换为python列表并返回。
如果被发现,this thread。但是它假设我们在编译时知道类型。
但是,是否有可能检索元素的ctype类型?
我有一个至少包含一个元素的python列表。我想做这样的事
import ctypes
arr = (type(pyarr[0]) * len(pyarr))(*pyarr)这显然不起作用,因为type()不返回一个与ctype兼容的类。但是,即使列表包含直接从ctype创建的对象,上面的代码也不能工作,因为它是类型的对象实例。
有什么办法来执行这个任务吗?
编辑
好的,这是对我有用的代码。我使用它将输入分区从comtype服务器方法转换为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)至少需要一个元素。
发布于 2012-03-30 00:48:39
我认为这是不可能的,因为多个类型映射到单个Python类型。例如,c_ int /c_long/c_ulong/c_ulonglong都映射到Python。你会选择哪种类型?您可以创建您的首选项的地图:
>>> 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_可以告诉ctype数组的类型。
>>> arr._type_
<class 'ctypes.c_double'>https://stackoverflow.com/questions/9931452
复制相似问题