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

转载于:https://www.cnblogs.com/Yjianyong/archive/2010/08/05/1792976.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值