C#-内存拷贝功能

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

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

using System.Runtime.InteropServices;

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

[StructLayout(LayoutKind.Sequential)]
class Cup
{
    public float volume;
    public float height;
    public float weight;
    public float identifier;
}

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

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

调用方法:

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

 

  

  

 

posted @ 2023-01-13 17:15  [春风十里]  阅读(664)  评论(0编辑  收藏  举报