C++ 中本机数组的 Memcpy 到托管数组命令行界面
我这样做对吗?
我得到一个指向本机数组的指针,需要复制到托管数组。将 memcpy() 与 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 的实际长度,因此不必担心这方面。查看代码,数组是从向量复制的。所以我可以安全地设置托管数组的大小。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你做得几乎是正确的:
Marshal::Copy 不安全,也不那么快。在托管 C++ 中始终使用固定指针。
编辑:如果需要,您可以先检查长度以确保 memcpy 不会超出范围,例如:
You are doing it almost right:
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.:
这有效,但不安全。当你得到arrayCount错误时,你会把垃圾收集堆炸成碎片。很难诊断。
Marshal::Copy() 既安全又快速。
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.