Memcpy native array for managed array in C ++ CLI

Am I doing it right?

I get a pointer to my own array and should copy to a managed array. Use memcpy () with 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 the pArray, so it doesn't really care about this aspect. I looked at the code and the array is copied from the vector. Therefore, I can safely set the size of the managed array.

+8
c ++ native memcpy c ++ - cli
source share
2 answers

You do this almost right:

 pin_ptr<Byte> pinPtrArray = &ManagedClass.ByteArray[ManagedClass.ByeArray->GetLowerBound(0)]; 

Marshall :: Copy is not safe and not so fast. Always use pinned pointers in managed C ++.

Edit:. If you want, you can check the length to make sure memcpy will not exceed the border, for example:

 if (arrayCount > ManagedClass.ByteArray.Length) (throw Out of bounds copy exception) 
+3
source share

It works, but not safe. You will blow up the trash heap into habits when you get an arrayCount error. It is very difficult to diagnose.

Marshall :: Copy () is safe and fast.

+11
source share

All Articles