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