In C#, when receiving byte array data from a C/C structure, you need to convert the array into a compatible C# structure. The following methods provide an efficient conversion path.
This method involves fixing a byte array and using Marshal.PtrToStructure to convert the bytes directly into a C# structure.
<code class="language-csharp">NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); return stuff; } finally { handle.Free(); } }</code>
This generic version allows conversion of any struct type from a byte array:
<code class="language-csharp">T ByteArrayToStructure<T>(byte[] bytes) where T : struct { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } }</code>
For simple applications, use unsafe fixed arrays:
<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 functions similarly to Marshal.PtrToStructure, allowing reading data from byte arrays. However, it incurs some additional overhead and is generally not recommended for performance-critical applications. Marshal.PtrToStructure operates directly on raw bytes without intermediate conversion, so performance is faster.
The above is the detailed content of How to Efficiently Convert C/C Data Structures from Byte Arrays to C# Structures?. For more information, please follow other related articles on the PHP Chinese website!