Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ctypes结构,字节对齐_Python_Ubuntu_Ctypes - Fatal编程技术网

Python ctypes结构,字节对齐

Python ctypes结构,字节对齐,python,ubuntu,ctypes,Python,Ubuntu,Ctypes,我使用ctypes模块来定义一个类似C的结构 class AtomPayload(ctypes.LittleEndianStructure): _pack_ = 1 _fields_ = [ ("address", ctypes.c_uint8, 8), ("mask", ctypes.c_uint8, 3), ("regL", ctypes.c_uint8, 5),

我使用ctypes模块来定义一个类似C的结构

    class AtomPayload(ctypes.LittleEndianStructure):
        _pack_ = 1
        _fields_ = [ ("address",    ctypes.c_uint8,  8),
             ("mask",       ctypes.c_uint8,  3),
             ("regL",       ctypes.c_uint8,  5),
             ("regH",       ctypes.c_uint8,  1),
             ("rw",         ctypes.c_uint8,  1),
             ("reserved",   ctypes.c_uint8,  6),
             ("param1",     ctypes.c_int32, 16),
             ("param2",     ctypes.c_int32, 16),
             ("param3",     ctypes.c_int16, 16)]
但是这种结构的大小在Windows和Ubuntu中有不同的结果

在Ubuntu中,输出是10,而在Windows中是9。任何人都知道如何让它在Ubuntu中工作。属性包在Ubuntu中不起作用吗?

如果我(在Ubuntu上)这样测试您的示例:

import codecs
p = AtomPayload()
p.param1 = 0x1111
p.param2 = 0x2222
p.param3 = 0x3333
print(codecs.encode(bytes(p), 'hex'))
它产生:

b'00000011110022220000'
我不确定这里到底发生了什么,这可能是ctypes中的一个bug。可能是未对齐的位字段导致的问题

无论如何,将32位字段拆分为两个16位整数对我来说似乎是不必要的,这应该会产生相同的结果:

class AtomPayload(ctypes.LittleEndianStructure):
        _pack_ = 1
        _fields_ = [
             ("address",    ctypes.c_uint8,  8),
             ("mask",       ctypes.c_uint8,  3),
             ("regL",       ctypes.c_uint8,  5),
             ("regH",       ctypes.c_uint8,  1),
             ("rw",         ctypes.c_uint8,  1),
             ("reserved",   ctypes.c_uint8,  6),
             ("param1",     ctypes.c_int16, 16),
             ("param2",     ctypes.c_int16, 16),
             ("param3",     ctypes.c_int16, 16)]
现在我得到:

b'000000111122223333'