在Python 2中使用ctypes时出现的偏移问题

问题描述 投票:0回答:1

我正在尝试读取小位图(“ test1.bmp”)的标题。我很快找到了结构。但是,当我尝试使用ctypes的Structure在Python 2.7中实现它时,会发生一些奇怪的事情:。,size“ -ulong的偏移量向前移动了2个字节。(请参见下文)

>>> BMPHeader.size
<Field type=c_ulong, ofs=4, size=4>

,, ofs“应该为2,因为,,, size”在,, id“ -char * 2之后。这会产生错误:

ValueError: Buffer size too small (14 instead of at least 16 bytes)

什么使“ ,, size”-偏移量偏移2个字节?

这是我的代码:

from ctypes import *

filename = "test1.bmp"
data     = None

with open(filename, "rb") as file:
    data = file.read()

class BMPHeader(Structure):

    _fields_ = [
        ("id",       c_char * 2),
        ("size",     c_ulong),
        ("reserved", c_ulong),
        ("offset",   c_ulong)]

    def __new__(self, data_buffer=None):
        return self.from_buffer_copy(data_buffer)

    def __init__(self, data_buffer):
        pass

header = BMPHeader(data[:14])

P.S .:请原谅我的英语(不是母语)。当我使用标头等时,我还是一个初学者,所以很有可能这只是我的错误代码。

python bitmap header ctypes offset
1个回答
1
投票

默认情况下,出于对齐目的,结构具有填充。在您的情况下,它将在idsize之间添加2个填充字节。由于您尝试读取的文件没有任何填充,因此您需要在结构中将其关闭。为此,请在_pack_ = 1下添加class BMPHeader(Structure):

© www.soinside.com 2019 - 2024. All rights reserved.