I'm calling a method via interop that returns an out IntPtr
parameter. How can I get a byte*
for this IntPtr
so I can operate on it? I tried the following:
fixed(byte* ptr = (byte)myIntPtr)
but it didn't work. Any help would be appreciated!
I'm calling a method via interop that returns an out IntPtr
parameter. How can I get a byte*
for this IntPtr
so I can operate on it? I tried the following:
fixed(byte* ptr = (byte)myIntPtr)
but it didn't work. Any help would be appreciated!
You can simply write:
byte* ptr = (byte*)int_ptr;
You don't have to use the fixed keyword. You don't want to pin the IntPtr, do you?
myIntPtr.ToPointer()
I didn't want "unsafe code" in my application, so I did the following to convert an IntPtr to a byte[]. Given an IntPtr called "unsafeDataBlock":
var byteArray = new byte[dataBlockSize];
System.Runtime.InteropServices.Marshal.Copy(unsafeDataBlock, byteArray, 0, dataBlockSize);
This seemed to work for me, I wasn't using Interop but was still calling a managed C++ function from C Sharp. The managed C++ function however called unmanaged code so it accomplished the same thing as Interop.
Anyway, in the C++ function that was called from c-sharp, I used this code:
(anyPointerType*) pointer = (anyPointertype*) myIntPtr.ToPointer();
If you don't want unsafe code in your application, you'll have to use the methods in System.Runtime.InteropServices.Marshal
, or (even better) declare your interop functions' parameter types so the marshaling happens automatically.