创建实例时系统中如何分配非托管内存?
当从 C# 创建 COM 对象或任何其他非托管实例时,非托管内存如何在系统中分配?
How is unmanaged memory allocated in system when COM objects or any other unmanaged instances are created from C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CLR 为要实例化的 COM 对象创建运行时可调用包装器 (RCW)。这是一种从 .NET 到 COM 系统的互操作代理。因此,您创建的 COM 对象会被分配,并在 CLR 中创建对其的引用,并将其放在堆上。
您必须始终在保存 RCW 引用的类中实现 IDisposable,因为它们不会自动清除(包装器位于 .NET 堆上,但 COM 对象本身不在)。在包装器上调用
Dispose()
会释放 COM 对象。因此,不实现 IDisposable 会导致内存泄漏。The CLR creates a Runtime Callable Wrapper (RCW) for the COM objects you want to instantiate. This is a kind of interop proxy from .NET to the COM system. The COM object you create is therefore allocated and a reference to it created in the CLR, which puts it on the heap.
You must always implement
IDisposable
in the class that holds references to RCWs, because they are not automatically cleaned up (the wrappers are on the .NET heap, but the COM objects themselves are not). CallingDispose()
on the wrapper releases the COM objects. Not implementingIDisposable
therefore causes memory leaks.我的猜测是它们会导致调用操作系统在非托管堆上创建内存。 CLR 显然与它们无关,因为它们不受管理。
My guess is they result in a call to the OS to create their memory on the unmanaged heap. The CLR would obviously have nothing to do with them as they are unmanaged.