如何将 byte[] 转换为 IntPtr?

本文介绍了三种访问与字节数组相对应的IntPtr的方法:使用不安全的代码块访问直接指向字节数组的指针;使用GCHandle获得对象;通过LocalAlloc创建内存块并将数据封送到该内存块。

有几种方法可以访问与字节数组相对应的 IntPtr

第一种,使用不安全的代码块来访问直接指向字节数组的指针。
unsafe
{
    
byte [] test  =   new   byte [ 5 ];
    
fixed  ( byte *  p  =   & test[ 0 ])
    {
        
* =   0xff ;
    }
}

第二种,可以使用 GCHandle 来获得对象
ContractedBlock.gif ExpandedBlockStart.gif 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 创建内存块并将数据封送处理到该内存块
ContractedBlock.gif ExpandedBlockStart.gif 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
E-mail:  lisencool@gmail.com

声明:
这里集中了在WinCEWindows Mobile开发中的一些基本常识。我很乐意和大家分享,也希望大家提出意见,并给我投稿,我会第一时间替您发表并署上您的大名!

Announce:
Here collects general knowledge on WinCE and Windows mobile. I 'm very glad to share them with all friends, and also hope you can share your problems and opinions and contribute articles to me to share with others. I'll publish your articles and sign your name at the first time.

  


转载于:https://www.cnblogs.com/Lisen/archive/2009/09/28/1576009.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值