首頁 >後端開發 >C++ >如何有效率地將 C/C 資料結構從位元組數組轉換為 C# 結構?

如何有效率地將 C/C 資料結構從位元組數組轉換為 C# 結構?

DDD
DDD原創
2025-01-19 07:24:11829瀏覽

How to Efficiently Convert C/C   Data Structures from Byte Arrays to C# Structures?

從位元組數組讀取C/C 資料結構到C#

在C#中,從C/C 結構體接收位元組陣列資料時,需要將陣列轉換為相容的C#結構體。以下方法提供了高效率的轉換途徑。

使用Marshal.PtrToStructure

此方法涉及固定位元組數組並使用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的比較

BinaryReader的功能與Marshal.PtrToStructure類似,允許從位元組陣列讀取資料。但是,它會產生一些額外的開銷,通常不建議用於對效能要求高的應用程式。 Marshal.PtrToStructure直接操作原始字節,無需中間轉換,因此效能更快。

以上是如何有效率地將 C/C 資料結構從位元組數組轉換為 C# 結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn