C++ Struct Size unequal C++ Struct Size in C++/CLI

2019-06-21 03:24发布

问题:

my question refers to the problem mentioned in the title.

I have a simple struct in a header file that looks like this:

typedef struct
{
    WORD FileType;          // File ID (0x7000)
    WORD HeaderSize;        // Size of this file header in Bytes
    WORD HeaderVersion;     // yy.y
    ULONG FileSize;         // Size of the whole file in Bytes
    WORD ImageHeaderSize;   // Size of the image header in Bytes
    WORD ULX, ULY, BRX, BRY;// bounding rectangle of the image
    WORD NrOfFrames;        // self explanatory
    WORD Correction;        // 0 = none, 1 = offset, 2 = gain, 4 = bad pixel, (ored)
    double IntegrationTime; // frame time in microseconds
    WORD TypeOfNumbers;     // short, long integer, float, signed/unsigned, inverted, 
                            // fault map, offset/gain correction data, badpixel correction data
    BYTE x[WINRESTSIZE];        // fill up to 68 byte
} WinHeaderType;

If I call sizeof(WinHeaderType) in a C console application I get 68, but if I call the same function with the same parameter in C++/CLI I get 80.

Could someone explain this behaviour to me?

I'm pretty new to C++/CLI, in fact I never worked with it before (started a few days ago), but I need to create a dll for .NET applications.

Since it's my first post I hope I did not break any of the forum rules.

Greez, Mo

[EDIT] It just becomes stranger and stranger ...

First Row: C Console Application Output

Second Row, First Column: C/C++ Console Application I coded to check DataType sizes.

Second Row, Second Column: C++/CLI Console Application I coded to check DataType sizes.

Source of the first application: http://fbe.am/sId

Project Files of the last two applications: http://fbe.am/sIf

Someone an explanaition for this?!

回答1:

With default packing rules (/Zp8), the structure contains 12 bytes of padding to get the members aligned. Which ought to be good enough to explain the difference between 68 and 80. You'll have to eliminate the padding, use #pragma pack in the MSVC compiler:

#pragma pack(push, 1)
typedef struct {
   // .. etc
} WinHeaderType;
#pragma pack(pop)


回答2:

It's most probably related to the definition of WORD being different in both cases. BYTE, WORD and ULONG are not native C++ type, so check where/how there are defined.

BYTE is probably a single char. ULONG probably an unsigned long. But WORD is probably different in your case.