Python ctypesgen/ctypes:如何以单字节对齐方式将结构字段写入文件

moo*_*oog 4 python struct ctypes

使用 ctypesgen,我生成了一个结构体(我们称之为 mystruct),其字段定义如下:

[('somelong', ctypes.c_long),
 ('somebyte', ctypes.c_ubyte)
 ('anotherlong', ctypes.c_long),
 ('somestring', foo.c_char_Array_5),
 ]
Run Code Online (Sandbox Code Playgroud)

当我尝试将该结构的实例(我们称之为 x)写入文件时: open(r'rawbytes', 'wb').write(mymodule.mystruct(1, 2, 3, '12345')),我注意到写入文件的内容不是字节对齐的。

我应该如何将该结构写入文件以使字节对齐为 1 字节?

Mar*_*nen 5

_pack_=1先定义再定义_fields_

例子:

import ctypes as ct

def dump(t):
    print(bytes(t).hex())

class Test(ct.Structure):
    _fields_ = (('long', ct.c_long),
                ('byte', ct.c_ubyte),
                ('long2', ct.c_long),
                ('str', ct.c_char * 5))

class Test2(ct.Structure):
    _pack_ = 1
    _fields_ = (('long', ct.c_long),
                ('byte', ct.c_ubyte),
                ('long2', ct.c_long),
                ('str', ct.c_char * 5))

dump(Test(1, 2, 3, b'12345'))
dump(Test2(1, 2, 3, b'12345'))
Run Code Online (Sandbox Code Playgroud)

输出:

0100000002000000030000003132333435000000
0100000002030000003132333435
Run Code Online (Sandbox Code Playgroud)

或者,使用该struct模块。请注意,定义<输出等效的字节序非常重要_pack_=1。如果没有它,它将使用默认包装。

import struct
print(struct.pack('<LBL5s', 1, 2, 3, b'12345').hex())
Run Code Online (Sandbox Code Playgroud)

输出:

0100000002030000003132333435
Run Code Online (Sandbox Code Playgroud)