【问题标题】:how to know if type is a class _ctypes.PyCArrayType?如何知道类型是否是类_ctypes.PyCArrayType?
【发布时间】:2021-05-12 08:13:41
【问题描述】:

我正在尝试从 python 调用一些 c API。 我有一个类定义像

class X(ctypes.Structure):
    _fields_ = [
        ("member", ctypes.c_int * 5)
    ]

我想知道成员是否属于数组类型。为了做到这一点,我做了以下实验,但我无法检查 a 的类型是否为数组。

>>>
>>> import ctypes
>>> a = 5*ctypes.c_int
>>> type(a)
<class '_ctypes.PyCArrayType'>
>>> b = (type(a) == _ctypes.PyCArrayType)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ctypes' has no attribute 'PyCArrayType'
>>>

如何检查 a 的类型是否为数组?

【问题讨论】:

    标签: python python-3.x ctypes


    【解决方案1】:

    根据[Python.Docs]: class ctypes.Array(*args)强调是我的):

    数组的抽象基类

    翻译成代码:

    >>> import ctypes as ct
    >>>
    >>> I5 = ct.c_int * 5
    >>> I5.__mro__
    (<class '__main__.c_long_Array_5'>, <class '_ctypes.Array'>, <class '_ctypes._CData'>, <class 'object'>)
    >>> issubclass(I5, ct.Array)
    True
    >>>
    >>> i5 = I5()
    >>> isinstance(i5, ct.Array)
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      相关资源
      最近更新 更多