代码之家  ›  专栏  ›  技术社区  ›  netseng

如何从C中的byte[]获取IntPtr#

  •  149
  • netseng  · 技术社区  · 16 年前

    byte[] 一个方法需要 IntPtr

    7 回复  |  直到 11 年前
        1
  •  218
  •   Sam Chad    11 年前

    GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
    IntPtr pointer = pinnedArray.AddrOfPinnedObject();
    // Do your stuff...
    pinnedArray.Free();
    
        2
  •  142
  •   Andrius Bentkus    14 年前

    以下方法应该有效,但 在一个 unsafe 上下文:

    byte[] buffer = new byte[255];
    fixed (byte* p = buffer)
    {
        IntPtr ptr = (IntPtr)p;
        // Do your stuff here
    }
    

    小心: 您必须在 fixed 块。

        3
  •  101
  •   Richard Szalay    15 年前

    IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
    Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
    // Call unmanaged code
    Marshal.FreeHGlobal(unmanagedPointer);
    

    编辑: 此外,正如Tyalis指出的那样,您还可以使用 如果您可以选择不安全的代码

        4
  •  20
  •   Eric Robinson I_AM_PANDA    4 年前

    你可以使用 Marshal.UnsafeAddrOfPinnedArrayElement

    GCHandle 在传递给此方法之前。为了获得最佳性能,此方法不验证传递给它的数组;这可能会导致意外行为。

        5
  •  13
  •   dlchambers    11 年前

    以下是对@user65157的回答的一个转折(顺便说一句,+1):

    class AutoPinner : IDisposable
    {
       GCHandle _pinnedArray;
       public AutoPinner(Object obj)
       {
          _pinnedArray = GCHandle.Alloc(obj, GCHandleType.Pinned);
       }
       public static implicit operator IntPtr(AutoPinner ap)
       {
          return ap._pinnedArray.AddrOfPinnedObject(); 
       }
       public void Dispose()
       {
          _pinnedArray.Free();
       }
    }
    

    然后像这样使用它:

    using (AutoPinner ap = new AutoPinner(MyManagedObject))
    {
       UnmanagedIntPtr = ap;  // Use the operator to retrieve the IntPtr
       //do your stuff
    }
    

    我发现这是一种不忘调用Free()的好方法:)

        6
  •  0
  •   David Burg    14 年前

        7
  •  -2
  •   nexdev    5 年前

    在某些情况下,您可以在IntPtr的情况下使用Int32类型(或Int64)。如果可以的话,另一个有用的类是BitConverter。如果你想要什么,你可以使用BitConverter。例如ToInt32。

        8
  •  -6
  •   Alejandro Mezcua    16 年前
    推荐文章