3

使用 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 个字节?

4

1 回答 1

4

Define _pack_=1 before defining _fields_.

Example:

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'))

Output:

0100000002000000030000003132333435000000
0100000002030000003132333435

Alternatively, use the struct module. Note it is important to define the endianness < which outputs the equivalent of _pack_=1. Without it, it will use default packing.

import struct
print hexlify(struct.pack('<LBL5s',1,2,3,'12345'))

Output:

0100000002030000003132333435
于 2012-09-30T15:46:30.277 回答