How to get a field descriptor of type type from ctypes Structure or Union field

I have a structure with different data types. I would like to iterate through the fields of the structure, check the data type and set the field with the appropriate value.

I have access to the size and offset of the field through the .size and .offset attributes. How can I get the "type" attribute of this field? Using type (value) does not print the ctypes data type for a particular field. If I print the value, then I see the ctypes data type, but there seems to be no attribute directly for this.

How can I access the type field descriptor directly?

from ctypes import *

class A(Structure):
    _fields_ = [("one", c_long),
                ("two", c_char),
                ("three", c_byte)]

>>> A.one
<Field type=c_long, ofs=0, size=4>
>>> A.one.offset
0
>>> A.one.size
4
>>> type(A.one)
<class '_ctypes.CField'>

Ideally, I would like to get a field type similar to the fragment below ...

>>> A.one.type
c_long
+3
source share
2 answers

_fields_:

>>> for f,t in A._fields_:
...  a = getattr(A,f)
...  print a,a.offset,a.size,t
...
<Field type=c_long, ofs=0, size=4> 0 4 <class 'ctypes.c_long'>
<Field type=c_char, ofs=4, size=1> 4 1 <class 'ctypes.c_char'>
<Field type=c_byte, ofs=5, size=1> 5 1 <class 'ctypes.c_byte'>
+4

API ctypes. Field repr <Field type=c_long ..>, :

name = ((PyTypeObject *)self->proto)->tp_name;

self->proto c_long, Python 2.7 cfield.c, self->proto. :

  • nametype.
  • (yuck) <Field type=X getattr(ctypes, X) .

, (1), , , _typeof(cls, fld):

from ctypes import *

def typemap(cls):
    _types = dict((getattr(cls, t), v) for t, v in cls._fields_)
    setattr(cls, '_typeof', classmethod(lambda c, f: _types.get(f)))
    return cls

@typemap
class A(Structure):
    _fields_ = [("one", c_long),
                ("two", c_char),
                ("three", c_byte)]

print A._typeof(A.one), A._typeof(A.two), A._typeof(A.three)

:

<class 'ctypes.c_long'> <class 'ctypes.c_char'> <class 'ctypes.c_byte'>
+4
source

All Articles