簡體   English   中英

如何將結構編組為UInt16數組

[英]How to marshal a struct into a UInt16 Array

我知道您可以使用如下代碼將結構編組為字節數組:

public static byte[] StructureToByteArray(object obj)
{
    int len = Marshal.SizeOf(obj);
    byte[] arr = new byte[len];
    IntPtr ptr = Marshal.AllocHGlobal(len);
    Marshal.StructureToPtr(obj, ptr, true);
    Marshal.Copy(ptr, arr, 0, len);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

但是,如何將結構編組為包含16位字而不是字節的數組?

public static UInt16[] StructureToUInt16Array(object obj)
{
    // What to do?
}

執行此操作的不安全和安全方法:

static UInt16[] MarshalUInt16(Object obj)
    {
        int len = Marshal.SizeOf(obj);

        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(obj, ptr, true);

        UInt16[] arr = new UInt16[len / 2];

        unsafe
        {
            UInt16* csharpPtr = (UInt16*)ptr;

            for (Int32 i = 0; i < arr.Length; i++)
            {
                arr[i] = csharpPtr[i];
            }
        }

        Marshal.FreeHGlobal(ptr);
        return arr;
    }

    static UInt16[] SafeMarshalUInt16(Object obj)
    {
        int len = Marshal.SizeOf(obj);
        byte[] buf = new byte[len];
        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(obj, ptr, true);
        Marshal.Copy(ptr, buf, 0, len);
        Marshal.FreeHGlobal(ptr);

        UInt16[] arr = new UInt16[len / 2];

        //for (Int32 i = 0; i < arr.Length; i++)
        //{
        //    arr[i] = BitConverter.ToUInt16(buf, i * 2);
        //}

        Buffer.BlockCopy(buf, 0, arr, 0, len);

        return arr;
    }

更新以反映他人的智慧。

有什么理由不Buffer.BlockCopy字節數組中,然后使用Buffer.BlockCopy嗎? 我會說,那將是最簡單的方法。 誠然,您必須進行適當的復制,因此效率較低,但是我認為您不會找到更簡單的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM