Note: For background information please see this related question: How to get LINQPad to Dump() System.__ComObject references?
I am able to retrieve the CLSID of the RCW class corresponding to a COM object (obtained from another COM object, not initialized by my code) using IPersist.GetClassID()
.
Type.GetTypeFromCLSID()
always returns the weakly-typed System.__ComObject
, not the strongly-typed RCW class.
I need to get the System.Type
of the strongly-typed RCW class to be able to wrap the COM object with it using Marshal.CreateWrapperOfType()
.
Is this possible or is this a non-starter due to how COM interop works?
Well here is what I ended up putting together as a proof of concept, just a handful of extension methods, really. This relies on the COM object implementing
IPersist
and having an RCW class in one of the PIAs loaded in the currentAppDomain
.Used like this:
I get the following output:
Which was the desired result. Now to make this play nice with LINQPad (my original question).
Type.GetTypeFromCLSID()
just returns a dynamic COM wrapper.Strongly-typed RCW must be defined in the .NET space. It must be classes that are decorated with the ComImportAttribute. .NET can't create these classes automatically ex-hihilo. They are defined manually (in .NET code), or by PIAs, or by tlbimp, or by Reflection Emit mechanism for example, like all .NET types. There is no preset relation between a COM CLSID and .NET corresponding classes for the reason there may be multiple .NET classes corresponding to the same CLSID.
If you have these types available, what you could do is scan a defined set of namespaces and build a
Dictionary<Guid, Type>
from it for example.