开发者

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

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-&开发者_JAVA百科gt;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.


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.


You are doing it almost right:

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

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

Edit: If you want to, you can check the length to make sure the memcpy won't exceed the bounds first, e.g.:

if (arrayCount > ManagedClass.ByteArray.Length)
    (throw Out of bounds copy exception)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜