Game Development Reference
Pinning Memory with the Fixed Statement
The automatic memory management provided by the Garbage Collector runs in a
background thread, so you can never tell when memory will be assigned to a new
data location. This can create a serious problem when dealing with pointers,
because the pointers will not update their addresses when the memory changes,
resulting in pointers that point at incorrect or invalid memory blocks.
C# supports the fixed statement, which is used to signal that a particular variable
should not be touched by the garbage collector. This is known as memory pinning,
which means that the specified memory is pinned to a particular location, and that
you are guaranteed that the location will remain constant until the code exits the
fixed statement. The fixed statement has similar syntax to the using statement.
The following code shows the fixed statement being used.
byte data = new byte;
fixed (byte* dataPtr = data)
// Code using dataPtr here
Some situations require that you have two fixed variables that use each other. This
is perfectly acceptable by nesting fixed statements. The following code shows this
byte data1 = new byte;
byte data2 = new byte;
fixed (byte* data1Ptr = data1)
fixed (byte* data2Ptr = data2)
// Code using data1Ptr and data2Ptr here