python - 确定对象是否为 ctypes 数组

标签 python ctypes

我想编写一个函数,可以将原生 Python 列表或 ctypes 数组作为参数。我可以使用

检测前者
isinstance(the_parameter, list)

如何确定给定变量是否引用 ctypes 数组?

编辑:在将 ctypes 数组传递给我的函数的情况下,我只是想将其转换为列表。我意识到我可以做到

python_list = list(python_list_or_ctypes_array)

无论 the_parameter 是 Python 列表还是 ctypes 数组,它都会给出一个列表。我将把这个问题留在这里,因为我仍然对答案感兴趣。

最佳答案

isinstance(the_parameter, ctypes.Array) 将检查 ctypes 数组。

ctypes 定义了以下简单的标量类型(注意,它们是私有(private)的):

_SimpleCData # _type_: 'P' for void *
_Pointer     # _type_: ctypes.c_int
_CFuncPtr    # _flags_, _restype_, _argtypes_, _check_retval_

虽然您可以直接对这些类型进行子类化,但在大多数情况下,您应该使用现有的子类和工厂函数,例如 c_void_pPOINTERCFUNCTYPE

ctypes 定义了以下聚合类型:

Array        # _type_, _length_
Structure    # _fields_, _anonymous_, _pack_, _swappedbytes_
Union        # _fields_, _anonymous_, _pack_, _swappedbytes_

Array 子类通常使用 * 运算符通过序列重复创建,例如IntArray = c_int * 10。您可以改为使用以下内容:

class IntArray(ctypes.Array):
    _type_ = ctypes.c_int
    _length_ = 10

a = IntArray(*range(10))
a_list = a[:]

关于python - 确定对象是否为 ctypes 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101171/

相关文章:

python - 是什么让这个安全描述符变坏了?

python - 将指针从 python var 传递到 c lib

c++ - 如何使用 ctypes 将数组从 C++ 函数返回到 Python

python - 清理 python 切片?

python - 解析PDF文档

python - 通过 Jenkins 运行时在 docker 中产生 "java gateway process exited before sending the driver its port number"

python - python中关于gabor过滤器的代码

python - 具有特定输出的 Elasticsearch DSL 查询

python - gspread import_csv file_id 参数是什么?

Python ctypes.string_at 释放行为