Search code examples
c#.netmemory-managementunmanaged-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#?


Solution

  • 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). Calling Dispose() on the wrapper releases the COM objects. Not implementing IDisposable therefore causes memory leaks.