Casting a System.__ComObject in C# via reflection

后端 未结 2 1040
梦毁少年i
梦毁少年i 2021-01-03 03:38

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

相关标签:
2条回答
  • 2021-01-03 04:23

    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.

    0 讨论(0)
  • 2021-01-03 04:41

    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

    0 讨论(0)
提交回复
热议问题