Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Guide

Zero-Allocation Memory Reading in C# with Span<T> & MemoryMarshal

dotnet_native_aot
C# Veteran
MEMBER
Rep: 174
Datum pridruživanja: Sep 2021
Postovi: 16
Hvala: 62
prije 1 mjeseci · Jun 25, 2026 12:32 PM
#1

How to read native process memory in C# without creating Garbage Collector allocations:

CSHARP
public static unsafe T ReadMemory<T>(IntPtr hProcess, IntPtr address) where T : unmanaged {
    T val = default;
    ReadProcessMemory(hProcess, address, &val, sizeof(T), out _);
    return val;
}

// Reading arrays with stackalloc Span
Span<byte> buffer = stackalloc byte[1024];
ReadProcessMemory(hProcess, address, buffer, out int bytesRead);
ReadOnlySpan<float> matrix = MemoryMarshal.Cast<byte, float>(buffer);

Zero GC gen-0 allocations, execution latency matches C++!

ptr_arithmetic
C++ Wizard
MEMBER
Rep: 162
Datum pridruživanja: May 2018
Postovi: 73
Hvala: 42
prije 1 mjeseci · Jun 25, 2026 6:21 PM
#2

MemoryMarshal.Cast reinterprets bytes into floats with 0 copies. Pure performance.

vtable_slayer
Senior Reverser
MEMBER
Rep: 215
Datum pridruživanja: Mar 2018
Postovi: 86
Hvala: 61
prije 1 mjeseci · Jun 26, 2026 12:25 AM
#3

C# memory management has evolved so much in .NET 7/8.