在python中将ctypes结构转换为bytearray

Mar*_*naW 2 python arrays ctypes

有没有办法转换包含指向字节数组的指针的 Ctypes 结构?

class SRamAccess(ctypes.Structure):
    _fields_ = [('channel', ctypes.c_uint), ('offset', ctypes.c_uint), ('len', ctypes.c_uint), ('data', ctypes.c_char_p)]
Run Code Online (Sandbox Code Playgroud)

Mar*_*nen 6

只需将其传递给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')
Run Code Online (Sandbox Code Playgroud)

请注意,'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')
Run Code Online (Sandbox Code Playgroud)

请注意,最后 3 个字节是填充以使整个结构的大小为 4 个字节的倍数,因此此类结构的数组保持 4 字节整数在 4 字节边界上对齐。