Home / Forums / Reinterpreting Byte Arrays to Structs at Zero Cost with MemoryMarshal.Cast

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

Reinterpreting Byte Arrays to Structs at Zero Cost with MemoryMarshal.Cast

BytePusher
Memory & Performance
MEMBER
Rep: 209
Join Date: Dec 2025
Posts: 13
Thanks: 32
2y ago · Jan 8, 2024 5:15 PM
#1
When reading binary packet streams or file headers, using
CODE
BinaryReader
copies fields one by one.

Using
CODE
MemoryMarshal.Cast
to cast raw byte spans directly into structured types in O(0) time:


CSHARP
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public readonly record struct PacketHeader(uint Magic, ushort PacketType, uint PayloadLength, ulong Timestamp);

public static class FastPacketParser
{
    public static bool TryParseHeader(ReadOnlySpan<byte> rawBytes, out PacketHeader header)
    {
        // Cast ReadOnlySpan<byte> into ReadOnlySpan<PacketHeader>
        ReadOnlySpan<PacketHeader> headerSpan = MemoryMarshal.Cast<byte, PacketHeader>(rawBytes);
        
        if (headerSpan.IsEmpty)
        {
            header = default;
            return false;
        }

        header = headerSpan[0];
        return header.Magic == 0x504B5431; // 'PKT1'
    }
}


CODE
MemoryMarshal.Cast
performs bounds checking and reinterprets the span memory layout without allocating or copying a single byte!
BytePusher · Memory & Performance
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
The following users thanked BytePusher for this post:
NativeCoder
Low-Level C++ / ASM
VIP
Rep: 374
Join Date: Jun 2025
Posts: 12
Thanks: 20
2y ago · Jan 8, 2024 6:33 PM
#2
Just make sure your struct is marked
CODE
[StructLayout(LayoutKind.Sequential)]
and does not contain managed reference types (like string or class objects), otherwise
CODE
MemoryMarshal.Cast
will throw a runtime exception.
NativeCoder · Low-Level C++ / ASM
Passionate about cache locality, SIMD instructions, and raw ...
StructPacker
Binary Protocol Dev
MEMBER
Rep: 314
Join Date: May 2024
Posts: 7
Thanks: 19
2y ago · Jan 9, 2024 7:33 PM
#3
We use this in our custom binary asset loader. Reading 100,000 vertex mesh buffers takes literally 0.05 milliseconds because it is just a pointer reinterpret!
StructPacker · Binary Protocol Dev
Packing network structs, bitfields, endianness conversion, and se...