Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy unmanaged data into managed array

Tags:

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?

like image 255
JeffRSon Avatar asked Jun 19 '11 14:06

JeffRSon


2 Answers

As you've noted, Marshal::Copy (and .NET in general), is not const-safe.

However, the usual C and C++ functions are. You can write either:

array<byte>^ data_array =gcnew array<byte>(dataSize);
pin_ptr<byte> data_array_start = &data_array[0];
memcpy(data_array_start, data, dataSize);

or to avoid pinning:

array<byte>^ data_array =gcnew array<byte>(dataSize);
for( int i = 0; i < data_array->Length; ++i )
    data_array[i] = data[i];
like image 151
Ben Voigt Avatar answered Sep 30 '22 18:09

Ben Voigt


"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.

like image 30
Brandon Moretz Avatar answered Sep 30 '22 18:09

Brandon Moretz