利用C#Marshal类实现托管和非托管的相互转换

Marshal 类 

命名空间:System.Runtime.InteropServices 

提供了一个方法集,这些方法用于分配非托管内存、复制非托管内存块、将托管类型转换为非托管类型,此外还提供了在与非托管代码交互时使用的其他杂项方法。 Marshal 类中定义的 static 方法对于处理非托管代码至关重要。此类中定义的大多数方法通常由需要在托管和非托管编程模型之间提供桥梁的开发人员使用。例如,StringToHGlobalAnsi 方法将 ANSI 字符从指定的字符串(在托管堆中)复制到非托管堆中的缓冲区。该方法还分配大小正确的目标堆。 

struct和IntPtr的相互转换: 

tagCaptureFrame f = (tagCaptureFrame)Marshal.PtrToStructure (m.WParam, typeof(tagCaptureFrame)); 




struct和byte[]相互转换(用Marshal类实现) 

转载自:http://www.cnblogs.com/tuyile006/archive/2006/12/28/605962.html 

相当于序列化与反序列化,但是不用借助外部文件

1、struct转换为byte[]
static byte[] StructToBytes(object structObj) 
{ 
int size = Marshal.SizeOf(structObj); 
IntPtr buffer = Marshal.AllocHGlobal(size); 
try 
{ 
Marshal.StructureToPtr(structObj, buffer, false); 
byte[] bytes = new byte[size]; 
Marshal.Copy(buffer, bytes, 0, size); 
return bytes; 
} 
finally 
{ 
Marshal.FreeHGlobal(buffer); 
} 

}   
   2byte[]转换为struct
static object BytesToStruct(byte[] bytes, Type strcutType) 
{ 
int 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); 
} 
} 
原文地址:https://www.cnblogs.com/profession/p/4914481.html