C# provides the Memory<T>
struct, representing a chunk of memory, allowing you to work efficiently with arrays and spans. Combining Memory<T>
with unsafe code will enable you to perform low-level memory manipulation operations for performance-critical scenarios.
Below is an example that demonstrates copying data using Memory<T>
and unsafe code. In this example, Memory<T>
represents source and target arrays, and unsafe code is employed to perform a memory copy operation between the arrays. The fixed statement pins the arrays in memory to avoid them being moved by the garbage collector during unsafe operations.
While this technique can lead to performance improvements, it comes with risks and should be used cautiously. Unsafe code can introduce memory-related bugs and security vulnerabilities if not handled correctly. Understand the pitfalls thoroughly and consider using safer alternatives when possible.
using System;
public class Program
{
public static void Main()
{
int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] targetArray = new int[sourceArray.Length];
var sourceMemory = new Memory<int>(sourceArray);
var targetMemory = new Memory<int>(targetArray);
CopyMemory(sourceMemory, targetMemory);
Console.WriteLine(string.Join(", ", targetArray));
}
public static unsafe void CopyMemory(Memory<int> source, Memory<int> target)
{
fixed (int* srcPtr = source.Span)
fixed (int* tgtPtr = target.Span)
{
int* src = srcPtr;
int* tgt = tgtPtr;
for (int i = 0; i < source.Length; i++)
{
*tgt++ = *src++;
}
}
}
}