News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

Structures. Ha!

Started by 2-Bit Chip, November 25, 2009, 03:18:11 AM

Previous topic - Next topic

2-Bit Chip

Why, for in structures and required by functions, is there asking for the size of a structure?

And also, why is alignment needed? How do I know when I need to align?

sinsi

>Why, for in structures and required by functions, is there asking for the size of a structure?
Quite a few structures passed to a win32 api date back to windows 3 (believe it or not) and have grown over time
to add extras to the end. The api will look at the size of the structure and know what version your program expects.
Light travels faster than sound, that's why some people seem bright until you hear them.

MichaelW

QuoteWhy, for in structures and required by functions, is there asking for the size of a structure?

To expand on sinsi's reply, including the size of the structure in the structure is part of a mechanism for changing the structure without breaking the functions that use it. For example, the WNDCLASSEXA structure was changed going from Win 3.x to Win 4.0:

typedef struct tagWNDCLASSEXA {
    UINT        cbSize;
    /* Win 3.x */
    UINT        style;
    WNDPROC     lpfnWndProc;
    int         cbClsExtra;
    int         cbWndExtra;
    HINSTANCE   hInstance;
    HICON       hIcon;
    HCURSOR     hCursor;
    HBRUSH      hbrBackground;
    LPCSTR      lpszMenuName;
    LPCSTR      lpszClassName;
    /* Win 4.0 */
    HICON       hIconSm;
} WNDCLASSEXA, *PWNDCLASSEXA, NEAR *NPWNDCLASSEXA, FAR *LPWNDCLASSEXA;


Since the structure is allocated by the caller and may or may not include the hIconSm member, the called function needs to know the size so it can avoid accessing a non-existent member.

QuoteAnd also, why is alignment needed? How do I know when I need to align?

See Windows Data Alignment on IPF, x86, and x64.

One non-obvious point is that the API functions expect the structures passed to them to be aligned as detailed in the linked article.
eschew obfuscation

2-Bit Chip

I sincerely appreciate both of your help. Thank you. :bg