Stats

Contributors: 1 Monday, August 8, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Reading structures with Marshal

Download c# eBook

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.

Generic PtrToStructure:

public static T PtrToStructure<T>(IntPtr ptr);

T - structure type.

ptr - A pointer to an unmanaged block of memory.

Example:

NATIVE_STRUCT result = Marshal.PtrToStructure<NATIVE_STRUCT>(ptr);       
  • If you dealing with managed objects while reading native structures, don't forget to pin your object :)
 T Read<T>(byte[] buffer)
    {
        T result = default(T);
        
        var gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    
        try
        {
            result = Marshal.PtrToStructure<T>(gch.AddrOfPinnedObject());
        }
        finally
        {
            gch.Free();
        }
        
        return result;
    }