Reading structures with Marshal C# with Example



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. 
Generic PtrToStructure: 
 

public static T PtrToStructure(IntPtr ptr); 
T - structure type. 
ptr - A pointer to an unmanaged block of memory. 
Example: 
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); 
try 
{ 
result = Marshal.PtrToStructure(gch.AddrOfPinnedObject()); 
} 
finally 
{ 
gch.Free(); 
} 
return result; 
} 

0 Comment's

Comment Form

Submit Comment