I frequently encounter some definitions for Win32API structures (but not limited to it) that have a cbSize
member as in the following example.
typedef struct _TEST {
int cbSize;
// other members follow
} TEST, *PTEST;
And then we use it like this:
TEST t = { sizeof(TEST) };
...
or
TEST t;
t.cbSize = sizeof(TEST);
...
My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the cbSize
member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you.
What is the purpose of the cbSize
member in some C++ structures on Win32API?
It is used for versioning. A good example is the GetVersionEx call. You can pass in either an OSVERSIONINFO or OSVERSIONINFOEX. The OSVERSIONINFOEX is a superset of OSVERSIONINFO, and the only way the OS knows which you have passed in is by the dwOSVersionInfoSize member.
My initial guess is that this could potentially be used for versioning.
That's one reason. I think it's the more usual one.
Another is for structures that have variable length data.
I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.
It also lets the WIN32 API do a minimal amount of sanity checking on the data being passed in.
For example a commom mistake is for a WIN32 structure to be passed in with an incorrect or uninitialised cbSize and when this happens the WIN32 API usually just returns a failed result, rather than try to process what appears to be corrupted data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With