gpt4 book ai didi

c# - C# 是否清理 C++ 分配的内存?

转载 作者:可可西里 更新时间:2023-11-01 16:30:43 32 4
gpt4 key购买 nike

我有一个具有以下签名的假想 COM 对象

void MemAlloc(ref double[] test, int membercount)

在 C++ 中使用 new/malloc 分配内存。一旦这是在 C# 中,使用 RCW,我如何确保正确释放内存?我认为 .NET 很难释放,考虑到在 C++ 中,您需要知道它是否是用 new/malloc/mm_malloc 分配的,然后才能正确释放它。那么,清理我的 C++ 分配数组的适当方法是什么?谢谢。

最佳答案

我相信您应该使用 CoTaskMemAlloc() 来获取您想要从托管端显式释放的内存。一旦内存不再可用,CLR 将负责释放内存。如果您想明确释放它,您可以使用托管的 Marshal.CoTaskFree() 例程。

一般来说,互操作编码(marshal)拆收器和 CLR 遵守 COM 释放内存的约定;接收者负责释放内存。因此,如果内存返回给托管调用者,CLR/Interop 编码(marshal)拆收器通常会负责释放在 native 调用中分配的内存。

来自 Memory Management with the Interop Marshaler (msdn):

The interop marshaler always attempts to free memory allocated by unmanaged code. This behavior complies with COM memory management rules, but differs from the rules that govern native C++.

Confusion can arise if you anticipate native C++ behavior (no memory freeing) when using platform invoke, which automatically frees memory for pointers. For example, calling the following unmanaged method from a C++ DLL does not automatically free any memory.

The runtime always uses the CoTaskMemFree method to free memory. If the memory you are working with was not allocated with the CoTaskMemAlloc method, you must use an IntPtr and free the memory manually using the appropriate method.

关于c# - C# 是否清理 C++ 分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/685934/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com