使用此代码:
from ctypes import *
class Tracerec(BigEndianStructure):
def __repr__(self):
textlist = list()
for name, *dtype in self._fields_:
value = getattr(self, name)
if type(value) == int: textlist.append(f'{name}:0x{value:x}')
else: textlist.append(f'{name}:{value}')
fulltext = ' '.join(textlist)
return f'<{self.__class__.__name__}={fulltext}>'
def __getitem__(self, i):
if type(i)==str: return getattr(self, i)
return getattr(self, self._fields_[i][0])
def __len__(self):
return len(self._fields_)
class Mystruct(Tracerec):
_fields_ = [
('a', c_uint16),
('b', c_uint16),
('c', c_uint32),
]
buffer = b'\x01\x02\x03\x04\x00\x00\x05\x06'
x = Mystruct.from_buffer_copy(buffer)
x
我得到这个输出:
<Mystruct=a:0x102 b:0x304 c:0x506>
但是我希望它格式化为ctypes字节长度,但是sizeof(dtype)
只返回this type has no size
。期望输出的示例:
<Mystruct=a:0x0102 b:0x0304 c:0x00000506>
下面是我的最终解决方案(希望如此),它也支持使用位大小,数组类型也将分解:
以及输出:
请尝试
sizeof(*dtype)
并向左填充0:相关问题 更多 >
编程相关推荐