使用此代码:
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)
仅返回此类型没有大小
。所需输出的示例:
<Mystruct=a:0x0102 b:0x0304 c:0x00000506>
最佳答案
尝试 sizeof(*dtype)
和 0 左边距:
...
for name, *dtype in self._fields_:
value = getattr(self, name)
size = sizeof(*dtype) * 2
if type(value) == int: textlist.append(f'{name}:0x{value:0{size}x}')
...
关于python - 如何获取 python ctypes 结构成员的长度以格式化十六进制输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66072767/