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

Offset problem when using ctypes in Python 2

我正在尝试读取小位图 ("test1.bmp") 的 headers。我很快找到了结构。但是当我尝试使用来自 ctypes 的结构在 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"-offset 移动了 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.: 请原谅我的英语(不是母语)。在使用 headers 等时我也只是一个初学者,所以很可能这只是我的错误代码。

为了对齐目的,结构默认有填充。在您的例子中,它在 idsize 之间添加了 2 个字节的填充。由于您正在尝试读取没有任何填充的文件,因此您需要在结构中将其关闭。通过在 class BMPHeader(Structure):.

下添加 _pack_ = 1 来完成此操作