What is the meaning of this C ++ macro?

I cannot understand what this macro means:

#define DECLARE_HANDLE(n) typedef struct n##__{int i;}*n DECLARE_HANDLE(HWND); 

I learned from program C that:

"##" means connecting the parameter.

therefore the macro is:

 typedef struct HWND__{int i;}*HWND 

Is it correct?

If this is correct, what is the point of this proposal?

===================

Code from the Bombermaaan game (for Windows and Linux),
link http://sourceforge.net/p/bombermaaan/code/HEAD/tree/trunk/src/Bombermaaan/winreplace.h ,
line number 90.

+7
source share
5 answers

The main purpose of this design is to prevent misuse of pens. If all the descriptors are just void * or int or long long or some other basic type, you have nothing to interfere with using one and not the other. The pointer to struct HWND__ and the pointer to struct HBITMAP__ are not the same thing, so if you have the following code:

 HWND hwnd; HBITMAP hbmp; hbmp = GetBitmap(...); hwnd = hbmp; // gives compiler error. 

This is a fairly classic method, ensuring that you get unique types so that the API provider does not want to provide a true ad. Although I'm not quite sure why they even need the right structure declaration, you could possibly get away with it:

 #define DECLARE_HANDLE(n) struct n ## __; struct n ## __ *n; 

It also ensures that any Dereferece HWND will not be possible, as the compiler will object to the "use of an incomplete type".

+10
source

Your guess is correct.

You can verify this with the following simple test code.

 DECLARE_HANDLE(HWND); struct HWND__ s; HWND p = (HWND) malloc(sizeof(struct HWND__)); si = 20; p->i = 100; cout << "i valueis " << si<<" and " << p->i <<endl; 
+4
source

That's right.

This is used to declare an opaque pointer to an unknown structure.

I donโ€™t know why they just didnโ€™t declare it as

 typedef void* HWND; 

Perhaps for alignment problems, since structures can be aligned, but not basic types .
As mentioned above, declaring a type as a structure allows some kind of compilation type checking.
Clever!

+1
source

It defines HWND as a pointer to a struct HWND__ containing int i .

So now you can use the HWND type in your code.

0
source

DECLARE_HANDLE(HWND); really expanding to

 typedef struct HWND__{int i;}*HWND; 

Now you ask, what does it mean? Just divide the typedef into two steps:

 struct HWND__ { int i; }; typedef HWND__* HWND; // C++ only; for both C++ and C: typedef struct HWND__* HWND; 

Thus, it defines an HWND__ structure containing int (named i ) and declares an alias of type HWND as a pointer to HWND__ .

0
source

All Articles