I’m attempting to cast a System.__ComObject to an interface type using reflection. I have tried using Convert.ChangeType(Object,Type) but c# then throws this error:
System.InvalidCastException: Object
must implement IConvertible.
So is there any possible way to cast a general __ComObject using reflection to its correct type so i can then call its methods via reflection? And yes, it has to be done via a method which doesn’t involve telling the compiler ahead of time what the object type is!
In general, no.
The _ComObject needs to implement an interface which the .Net runtime knows about. This will either be an interface which you get from
QueryInterfaceorIDispatch.If it’s the former, you have to know what the interface is, and then you have to describe the interface to .Net using the ComImportAttribute on the interface.
If the COM object implements
IDispatch, you can dynamically invoke members on it. In .Net 4.0 and above, this can be done easily by using thedynamickeyword. If you are using an earlier version of .Net, you can callInvokeMember()on the type returned byGetType()or else cast toIReflectand use that interface to call methods.The best case is if you get a Runtime Callable Wrapper (RCW) for the COM object, either by running
tlbimp.exeyourself on the COM library or getting a Primary Interop Assembly (PIA) for it, usually from the COM library author.