使用 ctypesgen,我生成了一个结构体(我们称之为 mystruct),其字段定义如下:
[('somelong', ctypes.c_long),
('somebyte', ctypes.c_ubyte)
('anotherlong', ctypes.c_long),
('somestring', foo.c_char_Array_5),
]
当我尝试将该结构的一个实例(我们称之为 x)写入文件时:
open(r'rawbytes', 'wb').write(mymodule.mystruct(1, 2, 3, '12345')),我注意到写入文件的内容不是字节对齐的。
我应该如何将该结构写出到文件中,以使字节对齐为 1 个字节?
最佳答案
定义 _pack_=1
在定义 _fields_
之前.
例子:
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
或者,使用
struct
模块。请注意,定义字节顺序很重要 <
输出相当于 _pack_=1
.没有它,它将使用默认包装。import struct
print hexlify(struct.pack('<LBL5s',1,2,3,'12345'))
输出:
0100000002030000003132333435
关于struct - Python ctypesgen/ctypes : How to write struct fields to file in single byte alignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12659094/