使用 memcpy 复制托管结构

发布于 2024-08-27 05:18:57 字数 574 浏览 1 评论 0原文

我正在混合模式下工作(在一个程序集中托管 C++ 和 C++)。我正处于这样的情况。

ManagedStructure ^ managedStructure = gcnew ManagedStructure();
//here i set different properties of managedStructure 

然后我调用下面给出的“方法”并将其传递给“& ManagedStructure”

Method(void *ptrToStruct)
{
    ManagedStructure ^ managedStructure2 = gcnew ManagedStructure();
    memcpy(&managedStructure2 , ptrToStruct, sizeof(managedStructure2 ));
}

我对这种情况有以下问题。

1)这样使用memcpy安全吗?如果不是,它的替代方案是什么来实现相同的功能? (我无法更改“方法”定义)

2)我没有释放任何内存,因为这两个结构都是受管理的。还好吗?

I am working in mixed mode (managed C++ and C++ in one assembly). I am in a situation something like this.

ManagedStructure ^ managedStructure = gcnew ManagedStructure();
//here i set different properties of managedStructure 

then I call "Method" given below and pass it "& managedStructure"

Method(void *ptrToStruct)
{
    ManagedStructure ^ managedStructure2 = gcnew ManagedStructure();
    memcpy(&managedStructure2 , ptrToStruct, sizeof(managedStructure2 ));
}

I have following question about this scenario.

1) Is it safe to use memcpy like this? and if not what is its alternate to achieve same functionality? ( I can't change "Method" definition)

2) I am not freeing any memory as both the structures are managed. Is it fine?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

晨敛清荷 2024-09-03 05:18:57

您可以考虑使用复制构造函数或类似的东西。请查看这篇文章解释了一些可能有用的事情。
我假设你的内存模型没问题,因为它都是托管的。

You could look into using a copy constructor or something similar. Check out this article as it explains a few things that might be useful.
I would assume your memory model is OK since it's all managed.

明明#如月 2024-09-03 05:18:57

我不确定,但您可能需要在 memcpy 之前固定 ManagedStructure2,请查看 pin_ptr<> 的文档。如果未固定,GC 可能会发生在 memcpy 中间的单独线程上,从而导致间歇性错误。

I'm not sure but you might need to pin managedStructure2 before the memcpy, look at the docs for pin_ptr<>. If it's not pinned, GC might happen on a separate thread in the middle of your memcpy, resulting in an intermittent bug.

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