只需将其传递给bytearray()
:
>>> import ctypes
>>> class SRamAccess(ctypes.Structure):
... _fields_ = [('channel', ctypes.c_uint), ('offset', ctypes.c_uint), ('len', ctypes.c_uint), ('data', ctypes.c_char_p)]
...
>>> s = SRamAccess(1,2,3,b'blah')
>>> bytearray(s)
bytearray(b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\xf0 .\x1a\xed\x01\x00\x00')
# \______________/\______________/\______________/\______________/\________________________/
# 1 2 3 padding pointer64
请注意,“blah”不是结构的一部分。最后 8 个字节(64 位 Python)是指针地址,前面的 4 个字节用于填充,以将 8 字节指针与结构中的 8 字节偏移量对齐。
您需要结构中的一个数组才能查看数组内容:
>>> class SRamAccess(ctypes.Structure):
... _fields_ = [('channel', ctypes.c_uint), ('offset', ctypes.c_uint), ('len', ctypes.c_uint), ('data', ctypes.c_char * 5)]
...
>>> s = SRamAccess(1,2,3,b'blah')
>>> bytearray(s)
bytearray(b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00blah\x00\x00\x00\x00')
# \______________/\______________/\______________/\______/\__________/
# 1 2 3 blah padding
请注意,最后 3 个字节是填充,以使整个结构的大小成为 4 字节的倍数,因此此类结构的数组使 4 字节整数在 4 字节边界上保持对齐。