在C ++ CLI中将本机数组的Memcpy映射到托管数组 [英] Memcpy of native array to managed array in C++ CLI
本文介绍了在C ++ CLI中将本机数组的Memcpy映射到托管数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我这样做吗?
我得到一个指向本机数组的指针,需要复制到一个托管数组。使用memcpy()和pin_ptr。
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是pArray的实际长度,所以不是真的担心这方面。看看代码和数组是从向量复制的。
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.
推荐答案
你几乎可以做到:
pin_ptr<Byte> pinPtrArray = &ManagedClass.ByteArray[ManagedClass.ByeArray->GetLowerBound(0)];
Marshal :: Copy不安全,在托管C ++中始终使用固定指针。
Marshal::Copy is not safe and not as fast. Always use pinned pointers in managed C++.
编辑:如果需要,您可以检查长度以确保memcpy不会超过边界,例如:
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)
这篇关于在C ++ CLI中将本机数组的Memcpy映射到托管数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文