How to get IntPtr from byte in C#

I want to pass a byte[] to a method takes a IntPtr Parameter in C#, is that possible and how?


Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:

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

Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.

Edit: Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you

Another way,

GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// Do your stuff...

This should work but must be used within an unsafe context:

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
    IntPtr ptr = (IntPtr)p;
    // do you stuff here

beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.

You could use Marshal.UnsafeAddrOfPinnedArrayElement(array, 0) to get a memory pointer to the array.

Here's a twist on @user65157's answer (+1 for that, BTW):

I created an IDisposable wrapper for the pinned object:

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()

then use it like thusly:

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

I found this to be a nice way of not forgetting to call Free() :)

Marshal.Copy works but is rather slow. Faster is to copy the bytes in a for loop. Even faster is to cast the byte array to a ulong array, copy as much ulong as fits in the byte array, then copy the possible remaining 7 bytes (the trail that is not 8 bytes aligned). Fastest is to pin the byte array in a fixed statement as proposed above in Tyalis' answer.

In some cases you can use an Int32 type (or Int64) in case of the IntPtr. If you can, another useful class is BitConverter. For what you want you could use BitConverter.ToInt32 for example.

Need Your Help

collapse rows in dataframe w/NA values


I am trying to collapse rows a, b, and c in a dataframe that looks like this:

Why abstract does not work for interface implicit methods?

java interface abstract jls

While reading JLS Specification for Interfaces I came across following phrase:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.