如何在24位上具有不对齐的python Ctypes结构



我使用ctypes来获得一些结构的python表示。当使用位字段并且最终结构的大小为4字节(或更大(时,一切都很好。当涉及到一个用24位(3个字节(表示的单个值的结构时,使用位字段语法时会添加1个字节的填充,但使用数组时不会添加(请参阅下面的代码(。

from ctypes import *
class MyStructure(BigEndianStructure):
_fields_ = [
("vol", c_uint32, 24)
]
_pack_ = 1
class MyStructure2(BigEndianStructure):
_fields_ = [
("vol", c_uint8 * 3)
]
_pack_ = 1

c = MyStructure()
c.vol = 0xABCDEF
print(bytes(c)) # should be 24 bit 
print(len(bytes(c))) # should be 3
d = MyStructure2()
d.vol[0] = 0xAB
d.vol[1] = 0xCD
d.vol[2] = 0xEF
print(bytes(d)) # it is24 bit 
print(len(bytes(d))) # it is 3

输出为:

$python test.pyb'\xab\xcd\xef\x00'4.b'\xab\xcd\xef'3

我应该如何修改第一个结构,使其大小为3字节?

您不能使用位字段来实现这一点,但您可以使用属性使其看起来与字节数组一起工作。请注意,即使使用打包,位字段为int32_t value:24;的C结构也将是四个字节,因此请确保您的结构大小匹配。

from ctypes import *
class MyStructure(BigEndianStructure):
_fields_ = ("_vol", c_uint8 * 3),
@property
def vol(self):
return int.from_bytes(self._vol, 'big')
@vol.setter
def vol(self, value):
self._vol = tuple(value.to_bytes(3, 'big'))
c = MyStructure()
c.vol = 0xABCDEF
print(bytes(c)) # should be 24 bit 
print(len(bytes(c))) # should be 3
print(hex(c.vol))

输出:

b'xabxcdxef'
3
0xabcdef

最新更新