See Also: StructLayoutAttribute Members
You can apply this attribute to classes or structures.
The common language runtime controls the physical layout of the data fields of a class or structure in managed memory. However, if you want to pass the type to unmanaged code, you can use the System.Runtime.InteropServices.StructLayoutAttribute attribute to control the unmanaged layout of the type. Use the attribute with LayoutKind.Sequential to force the members to be laid out sequentially in the order they appear. For blittable types, LayoutKind.Sequential controls both the layout in managed memory and the layout in unmanaged memory. For non-blittable types, it controls the layout when the class or structure is marshaled to unmanaged code, but does not control the layout in managed memory. Use the attribute with LayoutKind.Explicit to control the precise position of each data member. This affects both managed and unmanaged layout, for both blittable and non-blittable types. Using LayoutKind.Explicit requires that you use the System.Runtime.InteropServices.FieldOffsetAttribute attribute to indicate the position of each field within the type.
C#, Visual Basic, and C++ compilers apply the LayoutKind.Sequential layout value to structures by default. For classes, you must apply the LayoutKind.Sequential value explicitly. The [<topic://cpgrfTypeLibraryImporterTlbimpexe>] also applies the System.Runtime.InteropServices.StructLayoutAttribute attribute; it always applies the LayoutKind.Sequential value when it imports a type library.
The following example demonstrates the use of the System.Runtime.InteropServices.StructLayoutAttribute, and the System.Runtime.InteropServices.FieldOffsetAttribute.
C# Example
using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct Point { public int x; public int y; } [StructLayout(LayoutKind.Explicit)] public struct Rect { [FieldOffset(0)] public int left; [FieldOffset(4)] public int top; [FieldOffset(8)] public int right; [FieldOffset(12)] public int bottom; } class NativeCodeAPI { [DllImport("User32.dll")] public static extern bool PtInRect(ref Rect r, Point p); } public class StructLayoutTest { public static void Main() { Rect r; Point p1, p2; r.left = 0; r.right = 100; r.top = 0; r.bottom = 100; p1.x = 20; p1.y = 30; p2.x = 110; p2.y = 5; bool isInside1 = NativeCodeAPI.PtInRect(ref r, p1); bool isInside2 = NativeCodeAPI.PtInRect(ref r, p2); if(isInside1) Console.WriteLine("The first point is inside the rectangle."); else Console.WriteLine("The first point is outside the rectangle."); if(isInside2) Console.WriteLine("The second point is inside the rectangle."); else Console.WriteLine("The second point is outside the rectangle."); } }
The output is
The first point is inside the rectangle.