Read C/C data structure from byte array to C#
This article describes how to fill byte array data derived from C/C structures into C# structures.
Using GCHandle and Marshal
This method is divided into three steps:
GCHandle.Alloc
to fix the location of the byte array in memory. Marshal.PtrToStructure
to convert a fixed memory address to a NewStuff
instance. handle.Free()
to release GCHandle
. Simplified code:
<code class="language-csharp">NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); NewStuff stuff; try { stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff; }</code>
Generic version:
<code class="language-csharp">T ByteArrayToStructure<T>(byte[] bytes) where T : struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff; }</code>
More simplified version (requires unsafe code block):
<code class="language-csharp">unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } }</code>
BinaryReader method
Using BinaryReader
may not be more performant than the Marshal
method. Both methods require the data to be correctly laid out and sized to be successfully converted into a NewStuff
structure.
The above is the detailed content of How to Efficiently Convert a C/C Data Structure from a Byte Array to a C# Struct?. For more information, please follow other related articles on the PHP Chinese website!