【问题标题】:How to get ctypes type object from an ctypes array如何从 ctypes 数组中获取 ctypes 类型对象
【发布时间】:2012-04-13 11:00:13
【问题描述】:

实际上,我正在尝试将 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) 至少需要一个元素。

【问题讨论】:

    标签: python arrays list types ctypes


    【解决方案1】:

    我不认为这是直接可能的,因为多个 ctypes 类型映射到单个 Python 类型。例如 c_int/c_long/c_ulong/c_ulonglong 都映射到 Python int。你会选择哪种类型?您可以根据自己的喜好创建地图:

    >>> 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'>
    

    【讨论】:

    • 你是对的。我的问题实际上是,我做了类似error = HRESULT();error = E_FAIL 的事情。然后错误被添加到我想要转换的列表中。问题是,E_FAIL 是 int 类型,而不是 HRESULT。所以error = HRESULT(E_FAIL)error = HRESULT(); (...) error.value = E_FAIL 都可以工作。
    • 非常感谢无证 arr._type_ 正是我所需要的
    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多