The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: 2-Bit Chip on November 25, 2009, 03:18:11 AM

Title: Structures. Ha!
Post by: 2-Bit Chip on November 25, 2009, 03:18:11 AM
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?
Title: Re: Structures. Ha!
Post by: sinsi on November 25, 2009, 10:14:17 AM
>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.
Title: Re: Structures. Ha!
Post by: MichaelW on November 25, 2009, 11:18:12 AM
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 (http://msdn.microsoft.com/en-us/library/aa290049(VS.71).aspx).

One non-obvious point is that the API functions expect the structures passed to them to be aligned as detailed in the linked article.
Title: Re: Structures. Ha!
Post by: 2-Bit Chip on November 25, 2009, 05:33:40 PM
I sincerely appreciate both of your help. Thank you. :bg