Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the cbSize member in Win32API structs

Tags:

c++

winapi

api

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?

like image 316
Jorge Ferreira Avatar asked Oct 09 '08 23:10

Jorge Ferreira


3 Answers

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.

like image 112
Rob Walker Avatar answered Nov 15 '22 15:11

Rob Walker


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.

like image 33
Michael Burr Avatar answered Nov 15 '22 15:11

Michael Burr


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.

like image 40
jussij Avatar answered Nov 15 '22 16:11

jussij