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

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类实现托管和非托管的相互转换_煮茶论道_百度空间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值