C#-内存拷贝功能

日常工作中需要将对象A的数据赋给对象B,常用做法就是字段/属性依次赋值,如果对象有很多个成员,依次写显然是个比较笨的方式。

下面使用内存拷贝功能来实现上述目的。引入命名空间:

1
using System.Runtime.InteropServices;

首先给出类Cup,内有四个变量:

1
2
3
4
5
6
7
8
[StructLayout(LayoutKind.Sequential)]
class Cup
{
    public float volume;
    public float height;
    public float weight;
    public float identifier;
}

创建对象C1和C2,此时C1有值,C2无值,需要把C1的值复制给C2:

1
2
3
4
5
6
7
8
9
10
11
12
13
byte[] raw = new byte[16];
Array.Copy(BitConverter.GetBytes(350f), 0, raw, 0, 4);
Array.Copy(BitConverter.GetBytes(15f), 0, raw, 4, 4);
Array.Copy(BitConverter.GetBytes(255f), 0, raw, 8, 4);
Array.Copy(BitConverter.GetBytes(1234f), 0, raw, 12, 4);
Cup c1 = new Cup()
{
    volume = BitConverter.ToSingle(raw, 0),
    height = BitConverter.ToSingle(raw, 4),
    weight = BitConverter.ToSingle(raw, 8),
    identifier = BitConverter.ToSingle(raw, 12),
};
Cup c2 = new Cup();

先将C1的值转换为字节数组Raw:

复制代码
 1         static byte[] StructToByte(object obj)
 2         {
 3             int size = Marshal.SizeOf(obj.GetType());//获取大小
 4             byte[] buffer = new byte[size];//创建字节数组
 5             IntPtr ip = Marshal.AllocHGlobal(size);//分配内存
 6             Marshal.StructureToPtr(obj, ip, false);//将结构数据拷贝到内存
 7             Marshal.Copy(ip, buffer, 0, size);//将内存数据拷贝到字节数组
 8             Marshal.FreeHGlobal(ip);//释放内存
 9             return buffer;
10         }
StructToByte
复制代码

再将Raw的值赋给C2,则C2和C1相同。

复制代码
1         static void ByteToStruct(object obj, byte[] bytes)
2         {
3             int size = Marshal.SizeOf(obj.GetType());//获取内存大小
4             IntPtr ip = Marshal.AllocHGlobal(size);//分配指定大小内存
5             Marshal.Copy(bytes, 0, ip, size);//将字节数据拷贝到内存
6             Marshal.PtrToStructure(ip, obj);//将内存数据拷贝到对象
7             Marshal.FreeHGlobal(ip);//释放内存
8         }
ByteToStruct
复制代码

调用方法:

1
2
byte[] raw = StructToByte(c1);
ByteToStruct(c2, raw);

 

  

  

 

posted @   [春风十里]  阅读(744)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示