Copy unmanaged data into managed array

c++-cli

I need to copy native (i.e. unmanaged) data (byte*) to managed byte array with C++/CLI (array).

I tried Marshal::Copy (data is pointed to by const void* data and is dataSize bytes)

array<byte>^ _Data=gcnew array<byte>(dataSize);
System::Runtime::InteropServices::Marshal::Copy((byte*)data, _Data, 0, dataSize);

This gives error C2665: none of the 16 overloads can convert all parameters. Then I tried

System::Runtime::InteropServices::Marshal::Copy(new IntPtr(data), _Data, 0, dataSize);

which produces error C2664: parameter 1 cannot be converted from "const void*" to "__w64 int".

So how can it be done and is Marshal::Copy indeed the "best" (simplest/fastest) way to do so?

Best Solution

"IntPtr" is just a wrapper around a "void *". You shouldn't need the new syntax, just use of the explicit conversion operator.

System::Runtime::InteropServices::Marshal::Copy( IntPtr( ( void * ) data ), _Data, 0, dataSize );

Should work.

Related Question