无法理解LARGE_INTEGER结构

时间:2022-10-29 01:33:45

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

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

#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;

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.

所以,我看到它的方式,取决于MIDL_PASS的设置与否,这是一个非常紧凑的结构,只有一个LONGLONG,或更有趣的情况,这成为一个联合。

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.

如果这是一个联合,对我来说仍然有意义,有两个访问可能性,一个LONGLONG在一个块中,一个结构有Low和Highpart。到现在为止还挺好。

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".

但我无法理解结构被声明两次,相同的事实。它们似乎都是匿名的,但后者可以通过“你”获得。

Now to my question:

现在问我的问题:

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.

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

2 个解决方案

#1


18  

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:

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

LARGE_INTEGER a;
a.LowPart = 1;

but if you want portable code, you need:

但如果你想要便携式代码,你需要:

a.u.LowPart = 1;

The union lets you use either.

工会允许你使用任何一个。

#2


2  

You could directly access the LowPart and HighPart without having to go via the u member. As:

您可以直接访问LowPart和HighPart,而无需通过u成员。如:

LARGE_INTEGER x;
x.HighPart = 42;

(Need to look up though if unnamed structs can be union members in Standard C.)

(如果未命名的结构可以是标准C中的联合成员,则需要查找。)

#1


18  

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:

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

LARGE_INTEGER a;
a.LowPart = 1;

but if you want portable code, you need:

但如果你想要便携式代码,你需要:

a.u.LowPart = 1;

The union lets you use either.

工会允许你使用任何一个。

#2


2  

You could directly access the LowPart and HighPart without having to go via the u member. As:

您可以直接访问LowPart和HighPart,而无需通过u成员。如:

LARGE_INTEGER x;
x.HighPart = 42;

(Need to look up though if unnamed structs can be union members in Standard C.)

(如果未命名的结构可以是标准C中的联合成员,则需要查找。)