Python 如何获得';类型';ctypes结构或联合字段中的字段描述符
我有一个具有不同数据类型字段的结构。我希望遍历结构字段,检查数据类型,并使用适当的值设置字段 我可以通过字段的.size和.offset属性访问字段的大小和偏移量。如何获取字段的“type”属性?使用类型(值)不会打印特定字段的ctypes数据类型。如果我打印值,那么我确实看到了ctypes数据类型,但似乎没有一个属性可以直接访问它 如何直接访问类型字段描述符Python 如何获得';类型';ctypes结构或联合字段中的字段描述符,python,types,ctypes,descriptor,Python,Types,Ctypes,Descriptor,我有一个具有不同数据类型字段的结构。我希望遍历结构字段,检查数据类型,并使用适当的值设置字段 我可以通过字段的.size和.offset属性访问字段的大小和偏移量。如何获取字段的“type”属性?使用类型(值)不会打印特定字段的ctypes数据类型。如果我打印值,那么我确实看到了ctypes数据类型,但似乎没有一个属性可以直接访问它 如何直接访问类型字段描述符 from ctypes import * class A(Structure): _fields_ = [("one", c_
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'>
ctypes API似乎不支持这一点。创建
字段
repr
时,将从嵌入类型中检索名称,如下所示:
name = ((PyTypeObject *)self->proto)->tp_name;
对于您的字段,成员self->proto
指向culong
,但我在Python2.7中找不到可以检索self->proto
本身值的地方。您可能被迫:
名称
->类型
创建自己的映射的repr只需使用\u字段
列表:
>>> 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'>
>>对于A.中的f,t.\u字段:
... a=getattr(a,f)
... 打印a、a、偏移量、a、尺寸、t
...
0 4
4 1
5 1
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'>
>>> 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'>