I have an application that uses Office interop assemblies. I am aware about the \"Runtime Callable Wrapper (RCW)\" managed by the runtime. But I am not very sure how the ref
I haven't seen the code for the RCW -- not even sure it's part of the SSCLI -- but I had to implement a similar system for tracking COM object lifetime in SlimDX and had to do a fair bit of research into the RCW. This is what I remember, hopefully it's reasonably accurate but take it with a touch of salt.
When the system first sees a COM interface pointer, it just goes to a cache to see if there is an RCW for that interface pointer. Presumably the cache would be using weak references, so as not to prevent finalization and collection of the RCW.
If there is a live wrapper for that pointer, the system returns the wrapper -- if the interface was obtained in a fashion that incremented the interface's reference count, presumably the RCW system would call Release() at this point. It has found a live wrapper, so it knows that wrapper is a single reference and it wants to maintain exactly one reference. If there is no live wrapper in the cache, it creates a new one and returns it.
The wrapper calls Release on the underlying COM interface pointer(s) from the finalizer.
The wrapper sits between you and the COM object, and handles all parameter marshaling. This also allows allow it to take the raw result of any interface method that is itself another interface pointer and run that pointer through the RCW caching system to see if it exists yet before returning you the wrapped interface pointer.
Unfortunately I don't have a good understanding of how the RCW system handles proxy object generation for sending stuff across application domains or thread apartments; it wasn't an aspect of the system I needed to copy for SlimDX.