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?
That's what the document says:
year
, 2 bytes.