大家好,我是陆砚码,今天咱们来聊聊C#中一个很实用但也挺头疼的话题:托管和非托管内存的交互。相信很多朋友在写上位机软件的时候,都遇到过这种情况:工业相机SDK返回的数据是图像数据的地址,也就是指针,这就是典型的非托管内存。咱们得学会怎么从这些指针中获取数据,才能写出更高级的上位机软件。
首先,我们来认识一下 Marshal 类
Marshal 类是.NET Framework中提供的一个类,专门用来处理托管内存和非托管内存之间的数据交换。下面我们来看看几个常用的方法:
1. 获取非托管内存中的数据大小
char a = '1';
int aNums = Marshal.SizeOf(a);
int aNums1 = Marshal.SizeOf(typeof(Int16));
2. 将数据从托管对象封送到非托管内存
使用 Marshal.AllocHGlobal 方法分配内存,然后使用 Marshal.StructureToPtr 方法将数据从托管对象封送到非托管内存。
Point p = new Point();
p.X = 1;
p.Y = 1;
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));
try
{
Marshal.StructureToPtr(p, pnt, false);
Point anotherP; // 创建一个新的Point
anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));
Console.WriteLine(
