Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
A struct with a StructLayout of Sequential or Explicit can be mapped directly into unmanaged
memory. Consider the following struct:
[StructLayout (LayoutKind.Sequential)]
unsafe struct MySharedData
{
public int Value;
public char Letter;
public fixed float Numbers [50];
}
The fixed directive allows us to
define fixed-length value-type arrays inline, and it is what takes us into
the unsafe realm. Space in this struct
is allocated inline for 50 floating-point numbers. Unlike with standard C#
arrays, NumberArray is not a
reference to an array—it is the
array. If we run the following:
static unsafe void Main()
{
Console.WriteLine (sizeof (MySharedData));
}
the result is 208: 50 4-byte floats, plus the 4 bytes for the
Value integer, plus 2 bytes for the
Letter character. The total, 206, is
rounded to 208 due to the floats being
aligned on 4-byte boundaries (4 bytes being the size of a float).