python实现struct_从c中创建的struct读取python中的struct

您可以使用

ctypes.Structure或

struct.Struct指定文件的格式.要从 C code in @perreal’s answer生成的文件中读取结构:

"""

struct { double v; int t; char c;};

"""

from ctypes import *

class YourStruct(Structure):

_fields_ = [('v', c_double),

('t', c_int),

('c', c_char)]

with open('c_structs.bin', 'rb') as file:

result = []

x = YourStruct()

while file.readinto(x) == sizeof(x):

result.append((x.v, x.t, x.c))

print(result)

# -> [(12.100000381469727, 17, 's'), (12.100000381469727, 17, 's'), ...]

请参阅io.BufferedIOBase.readinto().它在Python 3中受支持,但在2007年的Python 2.7中没有记录.

struct.Struct需要明确指定填充字节(x):

"""

struct { double v; int t; char c;};

"""

from struct import Struct

x = Struct('dicxxx')

with open('c_structs.bin', 'rb') as file:

result = []

while True:

buf = file.read(x.size)

if len(buf) != x.size:

break

result.append(x.unpack_from(buf))

print(result)

它产生相同的输出.

为避免不必要的复制,可以使用Array.from_buffer(mmap_file)从文件中获取结构数组:

import mmap # Unix, Windows

from contextlib import closing

with open('c_structs.bin', 'rb') as file:

with closing(mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_COPY)) as mm:

result = (YourStruct * 3).from_buffer(mm) # without copying

print("\n".join(map("{0.v} {0.t} {0.c}".format, result)))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值