Get IntPtr for a byte array

L

Logan McKinley

I have a third party Dll with a function which requires an IntPtr but the
data is in a byte array. I need to get the IntPtr for this byte array so I
can pass it into the function.

Thanks in advance,
~Logan
 
M

Mattias Sjögren

Logan,
I found the answer,
use GCHandle, code sample follows
----------------------------------------------------------------------------
-------------
//b is the byte array
//ToSend is an IntPtr that is set to the address of b
GCHandle gch = GCHandle.Alloc(b,GCHandleType.Pinned);
ToSend = gch.AddrOfPinnedObject();

Just don't forget to Free the GCHandle when you're done with it.

Another possible solution is to change the DLL function declaration to
take a byte array parameter instead of an IntPtr.



Mattias
 
O

Oscar Papel

try the fixed statement

fixed (byte *p=ByteArray) {
IntPtr MyIntPtr= (IntPtr)p;
SomeDllMethod(MyIntPtr);
}

don't forget to use /unsafe when compiling

Oscar
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top