C# 的內存拷貝

    public static class StructCopyer
    {
        //        相當於序列化與反序列化,但是不用藉助外部文件
        //1、struct轉換爲Byte[]
        public static Byte[] StructToBytes(Object structure)
        {
            Int32 size = Marshal.SizeOf(structure);
            IntPtr buffer = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.StructureToPtr(structure, buffer, false);
                Byte[] bytes = new Byte[size];
                Marshal.Copy(buffer, bytes, 0, size);

                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

        }

        //2、Byte[]轉換爲struct
        public static Object BytesToStruct(Byte[] bytes, Type strcutType)
        {
            Int32 size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.Copy(bytes, 0, buffer, size);

                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }

    }

 

注:此處的類或結構必須是順序和長度都相同。可以參考    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]

//3.

byte[] newm = new byte[retVal];
int t = 1234;
GCHandle h = GCHandle.Alloc(t, GCHandleType.Pinned);
IntPtr p = h.AddrOfPinnedObject();
Marshal.Copy(p, newm, 0, retVal); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章