why does sizeof() on this structure return 6? shouldn't it be 5?
[StructLayout(LayoutKind.Sequential)]
struct PacketResponse
{
public byte a;
public byte b;
public short c;
public byte d;
};
Printable View
why does sizeof() on this structure return 6? shouldn't it be 5?
[StructLayout(LayoutKind.Sequential)]
struct PacketResponse
{
public byte a;
public byte b;
public short c;
public byte d;
};
It looks like after the four bytes the size will only go up in two-byte increments. It's nothing I've ever read about before but try declaring these types:and then run this code:Code:[StructLayout(LayoutKind.Sequential)]
struct S1
{
public byte a;
};
[StructLayout(LayoutKind.Sequential)]
struct S2
{
public byte a;
public byte b;
};
[StructLayout(LayoutKind.Sequential)]
struct S3
{
public byte a;
public byte b;
public short c;
};
[StructLayout(LayoutKind.Sequential)]
struct S4
{
public byte a;
public byte b;
public short c;
public byte d;
};
[StructLayout(LayoutKind.Sequential)]
struct S5
{
public byte a;
public byte b;
public short c;
public byte d;
public byte e;
};
[StructLayout(LayoutKind.Sequential)]
struct S6
{
public byte a;
public byte b;
public short c;
public byte d;
public byte e;
public byte f;
};
[StructLayout(LayoutKind.Sequential)]
struct S7
{
public byte a;
public byte b;
public short c;
public byte d;
public byte e;
public byte f;
public byte g;
};
You'll see that sizes 5 and 7 are skipped, and I'm guessing all odd numbers after that too.CSharp Code:
MessageBox.Show(Marshal.SizeOf(typeof(S1)).ToString(), "S1"); MessageBox.Show(Marshal.SizeOf(typeof(S2)).ToString(), "S2"); MessageBox.Show(Marshal.SizeOf(typeof(S3)).ToString(), "S3"); MessageBox.Show(Marshal.SizeOf(typeof(S4)).ToString(), "S4"); MessageBox.Show(Marshal.SizeOf(typeof(S5)).ToString(), "S5"); MessageBox.Show(Marshal.SizeOf(typeof(S6)).ToString(), "S6"); MessageBox.Show(Marshal.SizeOf(typeof(S7)).ToString(), "S7");
Hmmm... just did a bit more testing and discovered that if you change the short to byte then odd numbered sizes are returned as you'd expect. There must be some sort of alignment issue causing padding to take place but I'm somewhat baffled.
OK, I don't know exactly what all the issues and implications are but I just changed this:which is implicitly the same as this:Code:[StructLayout(LayoutKind.Sequential)]
to this:Code:[StructLayout(LayoutKind.Sequential, Pack=0)]
and got a size of 5 for your original type. That means that the default packing pads a byte somewhere, while forcing a packing of 1 will not. I don't know whether overriding the default packing could cause an issue when passing your structure to unmanaged code or not.Code:[StructLayout(LayoutKind.Sequential, Pack=1)]
SWEET!Quote:
Originally Posted by jmcilhinney
thanks a lot man,... haha you know too much :D