我想编写一个函数,可以将原生 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_p
、POINTER
和 CFUNCTYPE
。
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/