python - 如何获取 python ctypes 结构成员的长度以格式化十六进制输出?

标签 python ctypes

使用此代码:

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/

相关文章:

python - 无法在 python (3.4) 中加载 dll 文件

python - Python中的快速互相关方法

Python - 提高 Itertools 排列计算的性能速度;重复=15

python - 根据包含另一列中多个类别值的一个列值拆分数据框

python - 将 Cassandra CQL3 与 Python Web 框架结合使用

Python ctypes.BigEndianStructure 无法存储值

Python ctypes keybd_event 模拟ctrl+alt+delete

python - 将 kivy 与 pywinauto 一起使用时出现 ctypes.ArgumentError

python - 在同一进程中启动 Django Channels Worker

Python ctypes加载错误: undefined symbol