python - 如何从 ctypes 数组中获取 ctypes 类型对象

标签 python arrays list types ctypes

实际上,我正在尝试将 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/

相关文章:

python - 使用SymPy进行迭代计算,针对不同的参数值求解相同的方程

c - C 中的结构体数组,非链表

list - 在 common lisp 中复制结构列表

Python - 类型错误 : expecting string or bytes object

Python Tkinter 闪烁标准窗口

c++ - 在C++/OpenCV中绘制频率直方图

java - 计数以 x 开头的字符串,并存储在 Array Android Studio 中

c# - 按元素的内容和长度对列表进行排序

.net - 如何在 VB.NET 中替换 List(Of String) 中的项目?

c++ - 构建 jsoncpp (Linux) - 给我们凡人的指令?