C# Fixed Buffers
A fixed statement pins an array or a string in memory and gives a pointer to its data. The pointer stays valid until the fixed block ends.
Sum an array through a fixed pointer
The fixed block pins the array. A loop adds each value through the pointer.
using System;
class Program
{
static void Main(string[] args)
{
int[] data = { 4, 5, 6 };
int sum = 0;
unsafe
{
fixed (int* p = data)
{
for (int i = 0; i < data.Length; i++)
{
sum = sum + *(p + i);
}
}
}
Console.WriteLine(sum);
}
}Write through a fixed pointer
A write through the pointer changes the array itself. The first element shows the new value after the block.
using System;
class Program
{
static void Main(string[] args)
{
int[] data = { 10, 20, 30 };
unsafe
{
fixed (int* p = data)
{
*p = 40;
}
}
Console.WriteLine(data[0]);
}
}Read characters from a fixed string
A string can be pinned in the same way. The pointer reads each character by index.
using System;
class Program
{
static void Main(string[] args)
{
string text = "hi";
unsafe
{
fixed (char* p = text)
{
Console.WriteLine(p[0]);
Console.WriteLine(p[1]);
}
}
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
int[] data = { 8, 6, 4 };
unsafe
{
fixed (int* p = data)
{
for (int i = data.Length - 1; i >= 0; i--)
{
Console.WriteLine(*(p + i));
}
}
}
}
}Key points
- The fixed statement pins managed data so its address cannot change while the block runs.
- Pinning stops the garbage collector from moving the data during a collection.
- A fixed block over an array gives a pointer to the first element.
- Pointer arithmetic and indexing reach the later elements through that pointer.
- A fixed block over a string gives a char pointer to its characters.
- The data is unpinned when the block ends, so no pointer from the block may be kept.
In this example, the array holds 8, 6, and 4. The fixed block pins the array and gives a pointer to the first value. The loop starts at the last index and moves down to zero. Each step prints the value the pointer reaches at that offset.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the fixed statement guarantee while its block runs?