如何在 python ctypes 中使用 c++ 头文件中的对象标识符

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

我有一个二进制文件,其结构由头文件描述。我需要用 python 解析文件。 我有以下 C++ 头文件:

...
#define DWORD unsigned int
...
// What is the purpose of this?:
#define MGTSIGNATURE    0x54474D

struct MGTMeasureHeader
{
    DWORD           Signature:24; 
    ...
}

在 python 中我创建了以下内容:

import ctypes

class MGTMeasureHeader(ctypes.Structure):
    
    _fields_ = [
        ("Signature", ctypes.c_uint, 24),
        ...
    ]

现在我通过以下方式读取文件:

with open('binaryfile', 'rb') as f:
    mgtmeasureheader = MGTMeasureHeader()
    f.readinto(mgtmeasureheader)

我不明白如何使用头文件中的行信息:

#define MGTSIGNATURE    0x54474D

这是什么意思以及如何在我的 python 代码中使用它?

python c++ ctypes
1个回答
0
投票

首先,你的包含文件看起来比现代 C++ 更接近 C 风格...无论如何,在 C 或 C++ 语言中,

#define
可以用来定义常量值。

这意味着您可以在 Python 代码中简单地声明它:

import ctypes

MGTSIGNATURE = 0x54474D

class MGTMeasureHeader(ctypes.Structure):
    ...
© www.soinside.com 2019 - 2024. All rights reserved.