csharp / expert
Snippet
Low-Level Memory Manipulation with Unmanaged Pointers
By using the 'unsafe' keyword and 'fixed' statement, C# allows direct pointer arithmetic. The 'fixed' block pins the managed array in memory, preventing the Garbage Collector from moving it while the pointer is active. This technique is used for ultra-fast buffer processing where index bounds checking would otherwise introduce performance penalties.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public unsafe class BufferProcessor{public void InvertBits(byte[] data){fixed (byte* pStart = data){byte* current = pStart;byte* pEnd = pStart + data.Length;while (current < pEnd){*current = (byte)(~(*current));current++;}}}}
Breakdown
1
fixed (byte* pStart = data)
Pins the object in memory and obtains a pointer to the first element.
2
*current = (byte)(~(*current));
Dereferences the pointer to perform a bitwise NOT operation directly on memory.