Memcpy of native array to managed array in C++ CLI

Soppus picture Soppus · Aug 4, 2011 · Viewed 9.5k times · Source

Am I doing this right?

I get a pointer to a native array and need to copy to a managed array. Use memcpy() with a pin_ptr.

unsigned char* pArray;
unsigned int arrayCount;
// get pArray & arrayCount (from a COM method) 

ManagedClass->ByteArray = gcnew array<Byte,1>(arrayCount)
pin_ptr<System::Byte> pinPtrArray = &ManagedClass->ByteArray[0];
memcpy_s(pinPtrArray, arrayCount, pArray, arrayCount);

arrayCount is the actual length of pArray, so not really worried about that aspect. Looked at the code and the array is copied from a vector. So I can set the managed array size safely.

Answer

Hans Passant picture Hans Passant · Aug 4, 2011

That works, but isn't safe. You'll blow the garbage collected heap to smithereens when you get arrayCount wrong. Very hard to diagnose.

Marshal::Copy() is safe and just as fast.