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

Struct Python ctypesgen/ctypes:如何以单字节对齐方式将结构字段写入文件,struct,ctypes,Struct,Ctypes,使用ctypesgen,我生成了一个结构(我们称之为mystruct),其中的字段定义如下: [('somelong', ctypes.c_long), ('somebyte', ctypes.c_ubyte) ('anotherlong', ctypes.c_long), ('somestring', foo.c_char_Array_5), ] 当我试图将该结构的一个实例(我们称之为x)写入文件时: 打开(r'rawbytes',wb').write(mymodule.mystru

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

[('somelong', ctypes.c_long),
 ('somebyte', ctypes.c_ubyte)
 ('anotherlong', ctypes.c_long),
 ('somestring', foo.c_char_Array_5),
 ]
当我试图将该结构的一个实例(我们称之为x)写入文件时: 打开(r'rawbytes',wb').write(mymodule.mystruct(1,2,3,'12345')),我注意到写入文件的内容没有字节对齐


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

在定义
\u字段之前定义
\u pack=1

例如:

from ctypes import *
from io import BytesIO
from binascii import hexlify

def dump(o):
    s=BytesIO()
    s.write(o)
    s.seek(0)
    return hexlify(s.read())

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

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

print dump(Test(1,2,3,'12345'))
print dump(Test2(1,2,3,'12345'))
输出:

0100000002000000030000003132333435000000
0100000002030000003132333435
0100000002030000003132333435

或者,使用
struct
模块。注意,定义endianness
非常重要,感谢您的详细回复。非常感谢!不客气!如果这回答了您的问题,您可以单击答案左侧的复选标记接受它。谢谢
0100000002030000003132333435