I have the following .NET value types:
[StructLayout(LayoutKind.Sequential)]
public struct Date
{
public UInt16 V;
}
[StructLayout(LayoutKind.Sequential
The info you get from the Marshal class is only relevant if the type actually gets marshaled. The internal memory layout of a managed structure is not discoverable through any documented means, other than peeking at the assembly code perhaps.
Which means the CLR is free to reorganize the layout of the structure and optimize the packing. Swapping the D and V fields makes your structure smaller due the alignment requirements of a double. It saves 6 bytes on your 64-bit machine.
Not sure why this would be an issue for you, it shouldn't be. Consider Marshal.StructureToPtr() to get the structure laid-out the way you want it.
Two things:
StructLayout(Sequential)
does not guarantee packing. You might want to use Pack=1
, otherwise 32 and 64bit platforms might be different.
and string is a reference, not a pointer. If the string length is always fixed, you might want to use fixed char arrays:
public struct MyArray // This code must appear in an unsafe block
{
public fixed char pathName[128];
}
If you need explicit layout... use explicit layout...
[StructLayout(LayoutKind.Explicit)]
public struct StringPair
{
[FieldOffset(0)] public String A;
[FieldOffset(8)] public String B;
[FieldOffset(16)] public String C;
[FieldOffset(24)] public Date D;
[FieldOffset(32)] public double V;
}