tags:

views:

8443

answers:

4

Hi All,

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

Thanks All

+7  A: 

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
Marshal.FreeHGlobal(unmanagedPointer);

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

Richard Szalay
Just to clarify, `Marshal.Copy` with that overload needs a start index. The call should be `Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);`
Aeolien
@Aeolien - Well caught!
Richard Szalay
+2  A: 

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

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
}
Tyalis
+10  A: 

another way:

GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
//do your stuff
pinnedArray.Free();
This solution works very well. Thanks a lot!
Dimitri C.
A: 

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.

Alejandro Mezcua