C # later binding and calling COM components

Source: Internet
Author: User

 

Record the method for calling the local COM component using the C # non-binding method, so that you can search for yourself and those in need.

By adding reference to com components directly in the vs project, I will not talk about it here, mainly emphasizingPost-binding.

 

Step 1: Obtain the type exposed by the COM component based on the progid of the COM component:

Type comtype = type. gettypefromprogid ("your_com_progid ");

Step 2: Create an object of the type provided by the COM component (the final purpose is to call the method of this object ):

Object comobj = system. activator. createinstance (comtype );

Here, we need to call a method of the COM component, including the type and object, so it is easy to think of reflection:

Method method = comtype. getmethod ("method_name ");

If (method! = NULL)

Method. Invoke (comobj, paramters );

 

However, for the. net com component and the non-. Net COM component, the comtype is different:

    • If the COM component is a. Net COM component, the above reflection call method is feasible;
    • If the COM component is written in other languages such as VB and C ++, the above method is not feasible. The reason is that the metadata of the COM type is not obtained during the running, and the comtype obtained will be the unified packaging type system. _ comobject of all unknown COM components. The system. _ comobject class does not contain the method of the component you want to call. Therefore, comtype. getmethod ("method_name") cannot obtain the member method with the given name.

The correct method is to use the comtype. invokemember method after obtaining comtype and comobj:

Object returnobj = comtype. invokemember ("method_name"

, Bindingflags. invokemethod

, Null

, Comobj

, Paramters );

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.