Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
Guide

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

dotnet_native_aot
C# Veteran
MEMBER
прадстаўнік: 174
Дата далучэння: Sep 2021
Паведамленні: 16
Дзякуй: 62
1 месяцаў таму · 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
прадстаўнік: 162
Дата далучэння: May 2018
Паведамленні: 73
Дзякуй: 42
1 месяцаў таму · Jun 25, 2026 6:21 PM
#2

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

vtable_slayer
Senior Reverser
MEMBER
прадстаўнік: 215
Дата далучэння: Mar 2018
Паведамленні: 86
Дзякуй: 61
1 месяцаў таму · Jun 26, 2026 12:25 AM
#3

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