简体   繁体   English

创建实例时如何在系统中分配非托管 memory?

[英]How is unmanaged memory allocated in system when instances are created?

How is unmanaged memory allocated in system when COM objects or any other unmanaged instances are created from C#?当从 C# 创建 COM 对象或任何其他非托管实例时,如何在系统中分配非托管 memory?

The CLR creates a Runtime Callable Wrapper (RCW) for the COM objects you want to instantiate. CLR 为您要实例化的 COM 对象创建运行时可调用包装器 (RCW)。 This is a kind of interop proxy from .NET to the COM system.这是一种从 .NET 到 COM 系统的互操作代理。 The COM object you create is therefore allocated and a reference to it created in the CLR, which puts it on the heap.因此,您创建的 COM object 被分配,并在 CLR 中创建了对它的引用,这将其放在堆上。

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).您必须始终在包含对 RCW 的引用的 class 中实现IDisposable ,因为它们不会自动清理(包装器位于 .NET 堆上,但 COM 对象本身不是)。 Calling Dispose() on the wrapper releases the COM objects.在包装器上调用Dispose()会释放 COM 对象。 Not implementing IDisposable therefore causes memory leaks.因此,不实现IDisposable会导致 memory 泄漏。

My guess is they result in a call to the OS to create their memory on the unmanaged heap.我的猜测是他们会调用操作系统在非托管堆上创建他们的 memory。 The CLR would obviously have nothing to do with them as they are unmanaged. CLR 显然与它们无关,因为它们是不受管理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM