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

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

]

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.

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

解决方案

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

Output:

0100000002030000003132333435

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值