如何将 byte[] 转换为 IntPtr?
有几种方法可以访问与字节数组相对应的 IntPtr。
unsafe
{
byte[] test = new byte[5];
fixed (byte* p = &test[0])
{
*p = 0xff;
}
}
{
byte[] test = new byte[5];
fixed (byte* p = &test[0])
{
*p = 0xff;
}
}
第二种,可以使用 GCHandle 来获得对象。
using System.Runtime.InteropServices;
byte[] test = new byte[5];
GCHandle hObject = GCHandle.Alloc(test, GCHandleType.Pinned);
IntPtr pObject = hObject.AddrOfPinnedObject();
if(hObject.IsAllocated)
hObject.Free();
第三种, 通过 LocalAlloc 创建内存块并将数据封送处理到该内存块。
[DllImport("coredll.dll",SetLastError=true)]
public static extern IntPtr LocalAlloc(uint uFlags, uint uBytes);
[DllImport("coredll.dll",SetLastError=true)]
public static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("coredll.dll",SetLastError=true)]
public static extern IntPtr LocalReAlloc(IntPtr hMem, uint uBytes, uint fuFlags);
public const uint LMEM_FIXED = 0;
public const uint LMEM_MOVEABLE = 2;
public const uint LMEM_ZEROINIT = 0x0040;
byte[] test = new byte[5];
IntPtr p = LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, (uint)test.Length);
if (p == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
Marshal.Copy(test, 0, p, test.Length);
}
--------------------------------------------------
李森 – listen |
声明: Announce: |
posted on 2009-09-28 22:07 listenlisten 阅读(9870) 评论(1) 编辑 收藏 举报