四联光电智能照明论坛

标题: C# 的内存拷贝 [打印本页]

作者: 风火石    时间: 2017-3-24 09:54
标题: C# 的内存拷贝
近段时间在C#是直接调用动态库比较多,由于有时又需要使用ActiveX控件,往往出现很多的同名的不同命名空间的类,结构等,对不同实体之类的转换是很烦的一件事,于是考虑到内存直接拷贝。

    /// <summary>
    /// 内存复制。
    /// </summary>
    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)]
作者: 风火石    时间: 2017-3-24 10:00
//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);
作者: 风火石    时间: 2017-3-24 10:03
C# 拷贝数组的几种方式
https://wenku.baidu.com/view/6e0bf7d15fbfc77da269b1fe.html




欢迎光临 四联光电智能照明论坛 (http://5xhome.com/) Powered by Discuz! X3.2