zoukankan      html  css  js  c++  java
  • 如何将 byte[] 转换为 IntPtr?


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

    第一种,使用不安全的代码块来访问直接指向字节数组的指针。
    unsafe
    {
        
    byte[] test = new byte[5];
        
    fixed (byte* p = &test[0])
        {
            
    *= 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
    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.

      


  • 相关阅读:
    通过网页源代码看“饭否”的网站架构
    SD2.0课程等待时候的摘抄
    SD2.0阿里妈妈的研发过程
    转:编程8字专静谦筹悟慎透恒
    SD2.0第一天总体印象
    SD2.0《Web2.0网站性能调优实践》貌似是抄袭的文章
    SD2.02个课合成一个课
    SD2.0第2天总体印象
    variant
    [zz]C++程序员的阅读清单
  • 原文地址:https://www.cnblogs.com/Lisen/p/1576009.html
Copyright © 2011-2022 走看看