'C++/CLI Conversion of byte* to Managed Byte[]

I'm in a C++/CLI project, and I have a byte* variable that I want to fully convert into a managed array<byte> as efficiently as possible.

Currently, the only way that I've seen is to manually create the managed array<byte> object, and then copy individual bytes from the byte* variable, as shown below:

void Foo(byte* source, int bytesCount)
{
   auto buffer = gcnew array<byte>(bytesCount);

   for (int i = 0; i < bytesCount; ++i)
   {
      buffer[i] = source[i];
   }
}

Is there any other way to do this more efficiently? Ideally, to not have to copy the memory at all.

If not, is there any way to do this more cleanly?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source