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

来源:互联网 发布:淘宝官方客服电话95188 编辑:程序博客网 时间:2024/05/16 06:51
Marshal 类
命名空间:System.Runtime.InteropServices
提供了一个方法集,这些方法用于分配非托管内存、复制非托管内存块、将托管类型转换为非托管类型,此外还提供了在与非托管代码交互时使用的其他杂项方法。 Marshal 类中定义的 static 方法对于处理非托管代码至关重要。此类中定义的大多数方法通常由需要在托管和非托管编程模型之间提供桥梁的开发人员使用。例如,StringToHGlobalAnsi 方法将 ANSI 字符从指定的字符串(在托管堆中)复制到非托管堆中的缓冲区。该方法还分配大小正确的目标堆。
struct和IntPtr的相互转换:
tagCaptureFrame f = (tagCaptureFrame)Marshal.PtrToStructure(m.WParam, typeof(tagCaptureFrame));
struct和byte[]相互转换(用Marshal类实现)

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); }
}  

   2、byte[]转换为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); } }

 
引文来源  利用C#Marshal类实现托管和非托管的相互转换_煮茶论道_百度空间
http://lyh830612.blog.163.com/blog/static/1902733972011109104011676/
原创粉丝点击