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
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 QueryInterface
or IDispatch
.
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 the dynamic
keyword. If you are using an earlier version of .Net, you can call InvokeMember() on the type returned by GetType()
or else cast to IReflect and 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.exe
yourself on the COM library or getting a Primary Interop Assembly (PIA) for it, usually from the COM library author.
For any object to be type casted you need to be sure it belongs to that particular type. You can verify thisfirst by checking using "is" operator. http://msdn.microsoft.com/en-us/library/scekt9xw%28VS.71%29.aspx