C#C
C#3y ago
hugeman

❔ Unsafe Reading different types of structs from a byte array

I'm currently using the Unsafe class to help me read (and also write) different types of structs into a byte array. This is my read function so far:
public static unsafe T ReadStruct<T>(byte[] array, int offset, int size) where T : unmanaged {
    T value = default;
    Unsafe.CopyBlock(ref *(byte*) &value, ref array[offset], (uint) size);
    return value;
}


It works for me, even if the byte array contains something like 3 ints, a byte, and a long after than (21 byte elements). But I've also read about possible alignment issues which I'm not very familiar with... will my code run into problems at some point?
Was this page helpful?