Cool Goose
Cool Goose

Reputation: 998

how to know if type is a class _ctypes.PyCArrayType?

I am trying to call some c APIs from python. I have a class defined like

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

I wanted to know if member is of an array type. In order to do that I did following experiments but I can not check if type of a is an array.

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

How can I check if type of a is an array?

Upvotes: 1

Views: 887

Answers (1)

CristiFati
CristiFati

Reputation: 41116

According to [Python.Docs]: class ctypes.Array(*args) (emphasis is mine):

Abstract base class for arrays.

Translated to code:

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

Upvotes: 2

Related Questions