C#. [StructLayout(LayoutKind.Sequential, Pack = 4)] does not work when a structure contains ushort

83 Views Asked by At

My sample code:

~~~

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct OOP_DATE_T  //tag_Date
{
    public ushort year;       
    public byte month;       
    public byte mday;     
    public byte wday;       
};


public class Example
{
    public unsafe static void Main()
    {

        OOP_DATE_T ex = new OOP_DATE_T() { 
        year = 2022,
        month = 12,
        mday = 1,
        wday = 1
        };

        byte\* addr = (byte\*)&ex;
        Console.WriteLine("Size:      {0}", sizeof(OOP_DATE_T));


        //Console.WriteLine(Marshal.SizeOf\<OOP_DATE_T\>());

        Console.WriteLine("year Offset: {0}", (byte\*)&ex.year - addr);
        Console.WriteLine("month Offset: {0}", &ex.month - addr);
        Console.WriteLine("mday Offset: {0}", (byte\*)&ex.mday - addr);
        Console.WriteLine("wday Offset: {0}", (byte\*)&ex.wday - addr);
    }
}
// The example displays the following output:
//Size: 6
//year Offset: 0
//month Offset: 2
//mday Offset: 3
//wday Offset: 4

~~~

Four byte alignment should be a multiple of 4, therefore the expected size is 8

I can use both when Pack = 1 and Pack = 2

Adding an int variable to the structure can also work correctly.


    [StructLayout(LayoutKind.Sequential, Pack = 2)]
    public struct OOP_DATE_T  //tag_Date
    {
        public int aa;
        public ushort year;       
        public byte month;       
        public byte mday;   
        public byte wday;     

        
    };

When there is an int variable in the structure, the Pack attribute can work correctly.

why?

1

There are 1 best solutions below

2
On

That's what the document says:

The alignment of the type is the size of its largest element (1, 2, 4, 8, etc., bytes) or the specified packing size, whichever is smaller.

  1. The largest element is year, 2 bytes.
  2. The specified packing size is 4 bytes.
  3. 2 is smaller, so the alignment of the type is 2 bytes.