C# · 12月 26, 2021

C#清理C分配的内存吗?

我有一个具有以下签名的假设COM对象 void MemAlloc(ref double[] test,int membercount)

其中使用new / malloc在C中分配内存.一旦这是在C#中,使用RCW,如何确保内存释放正确?我认为.NET将很难释放,考虑在C中你需要知道它是否被分配了新的/ malloc / mm_malloc,然后才能正确地释放它.那么,什么是清理我的C分配的数组?谢谢.

解决方法 我相信你应该使用CoTaskMemAlloc()来显示从被管理端明确释放的内存. CLR将不再可用,释放内存.如果你想明确释放它,你可以使用托管的Marshal.CoTaskFree()例程.

一般来说,interop封送者和CLR遵守COM惯例来释放内存;收件人负责释放内存.因此,如果该内存返回给被管理的调用者,则CLR / Interop封送器通常将负责释放在本地调用中分配的内存.

从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.