Essential C# Interoperability  Suggest an edit

Reading structures with Marshal

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);
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;
}


Table Of Contents
22 Enum
25 GUID
107 Stream
108 Timers
150 Interoperability
  ↑ ↓ to navigate     ↵ to select     Esc to close