Reading structures with Marshal C# with Example
Marshal class contains a function named PtrToStructure, this function gives us the ability of reading structures by
an unmanaged pointer.
PtrToStructure function got many overloads, but they all have the same intention.
public static T PtrToStructure(IntPtr ptr);
T - structure type.
ptr - A pointer to an unmanaged block of memory.
NATIVE_STRUCT result = Marshal.PtrToStructure(ptr);
If you dealing with managed objects while reading native structures, don't forget to pin your object :)
T Read(byte buffer)
T result = default(T);
var gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
result = Marshal.PtrToStructure(gch.AddrOfPinnedObject());