© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
93 replies
hugeman

❔ Unsafe Reading different types of structs from a byte array

I'm currently using the
Unsafe
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;
}
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

❔ Read bits from a byte[] array
C#CC# / help
3y ago
❔ Sizing of Byte Arrays
C#CC# / help
3y ago
✅ Drawing WPF image from byte array
C#CC# / help
3y ago
❔ RecyclableMemoryStreams and Sending a Byte Array
C#CC# / help
3y ago