无法理解 LARGE_INTEGER 结构

2021-12-22 00:00:00 data-structures winapi c++

使用 C++ 和一些 Winapi 的东西,我遇到了这个家伙:

With C++ and some Winapi things, I encountered this guy:

#if defined(MIDL_PASS)
typedef struct _LARGE_INTEGER {
#else // MIDL_PASS
typedef union _LARGE_INTEGER {
    struct {
        DWORD LowPart;
        LONG HighPart;
    };
    struct {
        DWORD LowPart;
        LONG HighPart;
    } u;
#endif //MIDL_PASS
    LONGLONG QuadPart;
} LARGE_INTEGER;

所以,在我看来,取决于 MIDL_PASS 是否设置,这要么是一个非常紧凑的结构,其中只有一个 LONGLONG,要么更有趣的是,这变成了一个联合.

So, the way I see it, depending on MIDL_PASS being set or not, this is either a very compact struct with only a LONGLONG in it, or the much more interesting case, this becomes a union.

如果这是一个联合,对我来说仍然有意义,有两种访问可能性,一次是 LONGLONG 在一个块中,一次是具有 Low 和 Highpart 的结构.到目前为止一切顺利.

In case this is a union, it still makes sense to me, to have two possibilites of access, once the LONGLONG in one chunk, and once the struct with Low and Highpart. So far so good.

但是我无法理解结构被声明两次的事实,同样的.似乎他们都是匿名的,但后一个可以通过u"获得.

But I cannot make any sense out of the fact that the struct is declared twice, identically. It seems they are both anonymous, but the latter one is available via "u".

现在我的问题:

为什么定义了两个结构(冗余?),第一个的目的是什么,如果我什至无法访问它,因为没有绑定到任何类型/变量名.

Why are the two structs defined (redundantly?), what is the purpose of the first one, if I cannot even access it, due to not being bound to any type / variable name.

推荐答案

Microsoft 提供匿名结构作为 extension(他们的示例显示了另一个结构中的一个结构,但联合中的结构是相似的).如果您不介意基于其扩展名的不可移植代码,您可以使用以下内容:

Microsoft provides anonymous structs as an extension (their example shows one struct inside another struct, but a struct in a union is similar). If you don't mind non-portable code based on their extension, you can use things like:

LARGE_INTEGER a;
a.LowPart = 1;

但是如果你想要可移植的代码,你需要:

but if you want portable code, you need:

a.u.LowPart = 1;

联合让你可以使用.

相关文章