如何将结构编组到UInt16数组中

时间:2010-07-13 20:57:02

标签: c# struct marshalling

我知道您可以使用这样的代码将结构编组为字节数组:

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?
}

2 个答案:

答案 0 :(得分:2)

不安全和安全的方法:

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;
    }

更新以反映他人的智慧。

答案 1 :(得分:1)

是否有任何理由不编组成字节数组然后使用Buffer.BlockCopy?我会说,这将是最简单的方法。诚然,你必须进行适当的复制,因此效率较低,但我认为你找不到更简单的方法。

相关问题