Control data alignment in C# struct

#c-sharp #interop #stackoverflow

Written by Anders Marzi Tornblad

StackOverflow user bossman was trying to call functions in a DLL written in Assembler, and needed to control the alignment and placement of fields in a struct. As an example of what they wanted, they provided this C++ example:

__declspec( align( 16 ) )
double a[2] = { 10.2, 10.6 };

Interoperation with native code (interop for short) has been possible in .NET since .NET Framework version 1.1. By using a combination of the StructLayout attribute and the FieldOffset attribute, you have full control over how data is laid out:

[StructLayout(LayoutKind.Explicit, Pack = 16)]
public class MyDataClass
{
    [FieldOffset(0)]
    public double[] a = new double[] { 10.2, 10.6 };
}

According to a (now removed) MSDN article:

The System.Runtime.InteropServices.StructLayoutAttribute.Pack field determines the memory alignment of data fields of a target object.