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)]

posted @ 2010-08-05 11:40  Lance Yang  阅读(10800)  评论(0编辑  收藏  举报