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?
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];
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With