oliveryas01
oliveryas01

Reputation: 65

Getter for Windows handles

So I've been learning C++ for several months now, and I ran into a weird occurrence with my IDE. (Jetbrains CLion FTW!)

My IDE can generate getters for members, automatically determining the type, const or not, and other keywords. Obviously the generation is not perfect, so I find myself usually not using this feature. So at the moment I'm focusing on the Windows API, which requires working with handles. So something really weird happens when I generate a getter to a handle (HINSTANCE, HWND, HDC, etc...).

Say I have a member defined as follows:

HDC m_hDeviceContext;

Then when my IDE generates a getter it looks something like this:

const HDC__* getDeviceContext() const...

I'm so confused to why the type is HDC__. It makes sense that it is a pointer, hence a handle is declared as a pointer (typedef struct name##__ *name) in winnt.h.

Could anyone give me some insight on why this is occurring? Is it a bug with my IDE, because whenever I see examples of getters that return a handle, they usually just return straight that handle type.

Upvotes: 3

Views: 356

Answers (1)

chqrlie
chqrlie

Reputation: 144520

HDC is defined as a typedef for an opaque struct pointer:

typedef const struct HDC__ *HDC;

or in older windows version as a dummy type expanded from DECLARE_HANDLE(HDC):

typedef struct HDC__{int i;}*HDC;

The purpose if this definition is to prevent confusion between different types of handles that would all be just integers if typedefed as WORD or LONG, or DWORD. Making them pointers to different structures prevents compilation in case of mismatches. Microsoft has been doing this for at least 20 years.

Your IDE probably looks at the debugging information instead of parsing the header files, and it does not reverse the effect of the typedef.

In C++, struct tags are implicitly typedefed in the current namespace. So struct HDC__ also creates the type HDC__. For some reason your IDE assumes that. If you are compiling as C++, it should not be a problem. If you were compiling as C, too bad, this bug would probably be the least of your problems.

Upvotes: 4

Related Questions