windzhou
11/29/2017 - 7:27 AM

MarshalMatters.cs

字节数组和结构间的转换

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