Python ctypesgen / ctypes:如何以单字节对齐方式将结构字段写入文件 [英] Python ctypesgen/ctypes: How to write struct fields to file in single byte alignment

查看:208
本文介绍了Python ctypesgen / ctypes:如何以单字节对齐方式将结构字段写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using ctypesgen, I generated a struct (let's call it mystruct) with fields defined like so:

[('somelong', ctypes.c_long),
 ('somebyte', ctypes.c_ubyte)
 ('anotherlong', ctypes.c_long),
 ('somestring', foo.c_char_Array_5),
 ]

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

When I tried to write out an instance of that struct (let's call it x) to file: open(r'rawbytes', 'wb').write(mymodule.mystruct(1, 2, 3, '12345')), I notice that the contents written to the file are not byte-aligned.

我应该如何写出该结构以使字节对齐为1个字节?

How should I write out that struct to file such that the byte-alignment is 1 byte?

推荐答案

在定义 _fields _ 之前定义 _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

或者,使用 struct 模块。请注意,定义字节序< 很重要,它输出的等价项为 _pack_ = 1 。没有它,它将使用默认打包。

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

输出:

0100000002030000003132333435

这篇关于Python ctypesgen / ctypes:如何以单字节对齐方式将结构字段写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆