capypad
0 day streak
csharp / expert
Snippet

Advanced Interop with Unsafe Pointers

The 'unsafe' keyword allows C# to perform pointer arithmetic, similar to C++. Using 'fixed' pins the managed object in memory, preventing the Garbage Collector from moving it while you directly manipulate its memory addresses for maximum throughput in low-level scenarios.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
9
public unsafe void FastCopy(byte[] src, byte[] dest) {
fixed (byte* pSrc = src, pDest = dest) {
byte* ps = pSrc;
byte* pd = pDest;
for (int i = 0; i < src.Length; i++) {
*pd++ = *ps++;
}
}
}
Breakdown
1
fixed (byte* pSrc = src, pDest = dest)
Pins the arrays in memory to prevent GC movement during pointer access.
2
*pd++ = *ps++;
Directly dereferences pointers and increments them, mimicking low-level C memory copy.