在C#中,從C/C 結構體接收位元組陣列資料時,需要將陣列轉換為相容的C#結構體。以下方法提供了高效率的轉換途徑。
此方法涉及固定位元組數組並使用Marshal.PtrToStructure直接將位元組轉換為C#結構體。
<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>
此通用版本允許從位元組數組轉換任何結構體類型:
<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>
對於簡單的應用,可以使用不安全的固定數組:
<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的功能與Marshal.PtrToStructure類似,允許從位元組陣列讀取資料。但是,它會產生一些額外的開銷,通常不建議用於對效能要求高的應用程式。 Marshal.PtrToStructure直接操作原始字節,無需中間轉換,因此效能更快。
以上是如何有效率地將 C/C 資料結構從位元組數組轉換為 C# 結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!