Reading structures with Marshal

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents