[C #] Using Reflection to call COM components

Source: Internet
Author: User
The most common method to call a COM component is to add a reference to this component, but this will generate an accompanying DLL such as mycom. InterOP. dll in the final executable file. Program And adding references is that we can only reference COM components of a specific version, however, we often cannot determine whether the program runs on the machine with the corresponding version of COM components, which may cause the program to fail to run. How can we solve this problem?

First, we need to solve the version problem of the COM component. This requires that we do not directly use CLSID, but use progid to replace the COM component on the client to solve a considerable number of problems, that's simple.

As for how to remove the nasty DLL file, we need to use the reflection function provided by DOTNET. Code For example, assume that there is a COM component whose progid is "reflectioncom. testobj". This component has a unique method: String sayhello (string aname ):
Using System;

Using System. reflection;


Namespace Testconsole

{

Class Mainentrypoint

{

Static   Void Main ( String [] ARGs)

{

Object [] Oparams =   New   Object [] {"Leafyoung"} ;

Object Ocomobj = Activator. createinstance (

Type. gettypefromprogid ( " Reflectioncom. testobj " ));

Object Rez = Ocomobj. GetType (). invokemember ( " Sayhello " ,

Bindingflags. invokemethod,

Null ,

Ocomobj,

Oparams );

Console. writeline (REZ );

}

}

}

now, we can simply call any function of the COM component.
however, we need to see the shortcomings of this method. Due to the late binding, we cannot allow the compiler to perform any type checks, therefore, you can only know whether the program is right or wrong at runtime. Moreover, the COM component that can be called using this method must implement the idispatch interface, that is, it must be an automation component, if the component you want to call is a common COM component, then let's cry! Haha

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.