views:

591

answers:

2

If I have an unmanaged pointer and I want to transfer a specified number of bytes from that location to a Byte array, what is the best way to do this?

i.e. what is the equivalent of Marshal.PtrToString* methods but where the destination is a Byte()

Thanks

+1  A: 

Marshal.Copy has overloads for copying byte arrays to/from a pointer.

By Byte() is this interoperation with VB6 style COM? You why want to check the underlying COM type using the OLE-COM Viewer (included in the Windows SDK tools installed with VS) to open the VB created dll to look at that its typelib says.

Richard
Thanks that's perfect, I used the Marshal.Copy(IntPtr, Byte(), Int32, Int32) overload described here http://msdn.microsoft.com/en-us/library/ms146631.aspx
A: 

Try the following code

public static byte[] PtrToByteArray(IntPtr ptr, int len) {
  var array = new byte[len];
  for ( int i = 0; i < len; i++ ) { 
    array[i] = (byte)Marshal.PtrToStructure(ptr, typeof(byte));
    ptr = new IntPtr(ptr.ToInt64()+IntPtr.Size);
  }
}
JaredPar