windhuan
11/29/2017 - 7:27 AM

结构与字节数组的转换

    class MarshalMatters
    {
        public static T ReadUsingMarshalUnsafe<T>(byte[] data, int index = 0) where T : struct
        {
            unsafe
            {
                fixed (byte* p = &data[index])
                {
                    return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
                }
            }
        }

        public unsafe static byte[] WriteUsingMarshalUnsafe<selectedT>(selectedT structure) where selectedT : struct
        {
            byte[] byteArray = new byte[Marshal.SizeOf(structure)];
            fixed (byte* byteArrayPtr = byteArray)
            {
                Marshal.StructureToPtr(structure, (IntPtr)byteArrayPtr, true);
            }
            return byteArray;
        }
    }