将文件读入ctypes结构时出现问题

2024-09-28 22:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个原始的二进制文件,我正试图将它转换/移动到我创建的ctypes结构中,但是我似乎找不到合适的命令来执行它。你知道吗

我的代码的简化版本:


class Example_Structure(Structure):
    _fields_ = [
        ("a", c_uint16),
        ("b", c_uint16, 14),
        ("c", c_uint16, 2),
        ("d", c_uint16)
    ]

    #reading a file using open() and getting file size

    buf = create_string_buffer(file_size)
    file_object.readinto(buf)
    struct = Example_Structure()      
    memmove(addressof(struct),buf,48) #This is the line I'm unsure about
    # Maybe use cast(buf,struct) ?
    print(struct.a)

我通常在没有addressof(struct)的情况下在memmove行上得到"ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type",但是使用addressof只会为每个字段提供0。你知道吗

谢谢你的帮助

编辑: 我发现了一些成功的方法:

tmp = cast(addressof(buf),POINTER(struct)).contents

Tags: 文件sizeexampletype二进制ctypesstructurestruct
2条回答

比你想象的容易。ctypes.Structure支持缓冲区协议,因此您可以直接执行以下操作:

buf = Example_Structure()
file_object.readinto(buf)

示例:

from ctypes import *

class Example_Structure(Structure):
    _fields_ = [
        ("a", c_uint16),
        ("b", c_uint16, 14),
        ("c", c_uint16, 2),
        ("d", c_uint16)
    ]

# Create some raw test data
with open('test.bin','wb') as f:
    f.write(b'\x22\x33\xff\x7f\xaa\x55')

buf = Example_Structure()

with open('test.bin','rb') as file_object:
    file_object.readinto(buf) # Will read sizeof(buf) bytes from file

print(f'{buf.a:04x} {buf.b:04x} {buf.c:04x} {buf.d:04x}')

输出:

3322 3fff 0001 55aa

我想你的建筑应该是64号。但你甚至不用猜。使用sizeof使memmove语句

memmove(addressof(struct),buf,sizeof(struct)) 

它的一个很好的特性是,如果您对Example\u结构中的字段进行了更改,就不必返回并计算大小。你知道吗

最后,我建议您将变量从struct重命名为其他名称。如果您决定使用流行的struct module that is built into the standard library,可能会遇到命名冲突的问题。你知道吗

相关问题 更多 >