加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:09:21 所属栏目:百科 来源:网络整理
导读:我有一个具有以下签名的假设COM对象 void MemAlloc(ref double[] test,int membercount) 其中使用new / malloc在C中分配内存.一旦这是在C#中,使用RCW,如何确保内存释放正确?我认为.NET将很难释放,考虑在C中你需要知道它是否被分配了新的/ malloc / mm_mallo
我有一个具有以下签名的假设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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读