C++ 中本机数组的 Memcpy 到托管数组命令行界面

发布于 2024-11-27 17:01:37 字数 480 浏览 3 评论 0原文

我这样做对吗?

我得到一个指向本机数组的指针,需要复制到托管数组。将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只有一腔孤勇 2024-12-04 17:01:38

你做得几乎是正确的:

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

Marshal::Copy 不安全,也不那么快。在托管 C++ 中始终使用固定指针。

编辑:如果需要,您可以先检查长度以确保 memcpy 不会超出范围,例如:

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

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)
迷路的信 2024-12-04 17:01:37

这有效,但不安全。当你得到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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文