struct - Python ctypesgen/ctypes : How to write struct fields to file in single byte alignment

标签 struct ctypes

使用 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/

相关文章:

python-2.7 - Python ctypes : How to pass NULL as argument with format const char **

python - IPython 支持 ctypes 吗?

python - 使用 `as_ptr()` 时如何阻止内存泄漏?

c - 使用结构体数组成员二进制保存结构体 (C)?

pointers - Go struct literals,为什么这个是可寻址的?

c - 为什么结构按照最高数据类型分配大小?

c - C 中的结构和指针

c - 如何将位于结构数组内的一个指针内容复制到另一个指针

python - 处理 Ctype 中的默认参数

python - 帮助 python ctypes 和 nvapi