Search code examples
c++-cli

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?


Solution

  • You can't create a managed array from an unmanaged buffer without copying.

    However, you don't need to copy the individual bytes in a loop, though. You can pin the managed array (see pin_ptr) and then copy the bytes directly from the unmanaged buffer into the memory of the managed array, such as with memcpy() or equivalent.

    void Foo(byte* source, int bytesCount)
    {
       auto buffer = gcnew array<byte>(bytesCount);
    
       {
          pin_ptr<byte> p = &buffer[0];
          byte *cp = p;
          memcpy(cp, source, bytesCount);
       }
    
       // use buffer as needed...
    }