Go C # Interoperability Primer Series (iv): Calling COM components in C #

Source: Internet
Author: User

Transmission Door

C # Interop Series articles:

    1. C # Interoperability Primer Series (i): Introduction to Interoperability in C #
    2. C # Interoperability Primer series (ii): Invoke the Win32 function using platform invoke
    3. C # Interoperability Primer Series (iii): data marshaling in platform invoke
    4. C # Interoperability Primer Series (iv): Calling COM components in C #

Summary of the topic:

    • Introduction
    • How to call COM components in C #--Access Office Interop objects
    • An analysis of the implementation principle of calling COM components in C #
    • Error handling
    • Summary

First, Introduction

COM (Component object Modele, Component Object Model) is one of Microsoft's previously respected development technologies, so many of Microsoft's products now use COM components, such as Office,ie. But what if a program under the. NET platform wants to access a COM component in a way that implements a feature? It is because developers have this requirement that Microsoft supports interoperability between COM and managed code in the. NET framework, and this interoperability technology is COM interop. but COM Interop (COM interop) is a technique that not only supports the use of COM objects in managed code, but also supports the use of managed objects in COM, this topic is only for the. NET calls COM objects to introduce, because COM technology now uses a few, so how to use managed objects in COM will not be introduced in this series, if you need friends can refer to MSDN RELATED links: http://msdn.microsoft.com/zh-cn /library/3y76b69k (v=vs.100). aspx.

Here's a concrete example of how COM components are called in. NET.

Ii. How to call COM components in C #--Access Office Interop objects

Because many COM components are used in office products, here's an example of creating a Word document by calling a COM object in office and saving the created document to a file directory (adding " Microsoft.Office.Interop.Word 14.0.0.0 "This reference, 14.0.0.0 is an interop assembly that corresponds to Office 2010, and the 12.0.0.0 version corresponds to the office 2007 Interop assemblies, if you only have Office 2007 installed on your PC, you can only find the version of 12.0.0.0, if you have Office 2010 installed, you can find these two versions at the same time. )。 The specific code is as follows:

Using system;//add additional namespaces using Microsoft.office.interop.word;namespace COM Interoperability {    class program    {        static void Main (string[] args)        {            //Call COM object to create Word document            createworddocument ();        }        private static void Createworddocument ()        {            //start Word and make Word visible            application WordApp = new application () { Visible = true};            New Word document            wordApp.Documents.Add ();            Document WordDoc = wordapp.activedocument;            Paragraph para = WordDoc.Paragraphs.Add ();            Para. Range.Text = "welcome you, into learning Hard blog";            Save document            Object filename = @ "D:\learninghard.doc";            WORDDOC.SAVEAS2 (filename);            Close Word            worddoc.close ();            WordApp.Application.Quit ();}}}    

The result of the operation is:

You can now see the Word document you just created in the file directory you specified. With COM interop technology we can automate office operations.

Iii. analysis of the implementation principle of calling COM components in C #

From the example above, you can see that calling COM components in. NET is so convenient and simple that we simply cannot understand the rationale behind it, and the following describes the implementation principles and steps required to invoke COM components in managed code.

To run the above program you must add an interop assembly-"Microsoft.Office.Interop.Word 14.0.0.0"-and you can add this assembly by following these steps:

    • In Solution Explorer, right-click the references folder, and then click Add Reference .
    • On the. NETtab, select the latest version of Microsoft.Office.Interop.Word. For example, "Microsoft.Office.Interop.Excel 14.0.0.0". Click OK.

By adding a reference above, you can see thatMicrosoft.Office.Interop.Word.dll is a. NET assemblies, not COM components, this is a question that friends must have--not calling COM components? How do I invoke a. NET assembly in managed code? How could this be a. NET downgrade with a demo of COM components? But the fact is-- Microsoft.Office.Interop.Word.dll is indeed one. NET assembly, and it is also called an interop assembly of COM components, which contains metadata for the types defined in the COM component, and managed code calls the COM objects and interfaces indirectly by invoking the interfaces or objects exposed in the interop assembly. Because COM objects and interfaces are not directly used in managed code, the call to COM objects by managed code is done through the CLR's com Interop layer as the proxy, which is the RCW (the runtime callable Wrapper, Runtime callable wrapper), so calls to COM objects are done through the RCW, and the RCW does the work of activating COM objects and marshaling data between managed and unmanaged code (as you can see here, the RCW is.) NET platform and a proxy between COM components, many Microsoft technologies use proxies, such as WCF technology--the object that we create in code is actually just a proxy for the service, which is a method of accessing the true object's service through the proxy object. Speaking of Agent Technology, C # in the delegation is also a proxy implementation, at this time also think of the 23 design mode-proxy mode, but there are also many examples of agent in life, rental intermediary, proxy server, etc.). Here's a diagram to illustrate the principle of calling COM components in. NET:

About building interop assembly steps with the Tlblmp.exe tool, here I don't have much detail to tell you, so you can refer to MSDN for more instructions on how to use this tool: HTTP://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/TT0CF3SX (v=vs.80). aspx.

However, we can also use the built-in support in Visual Studio to complete the work of creating an interop assembly for a COM type library, and we just need to add a reference to the corresponding COM component to the. NET project in vs. At this point, VS will automatically convert the COM type library in the COM type library into the metadata in the assembly, and build the interop assembly for it in the bin directory of the project, so add COM references in VS, in fact the interop assemblies are referenced in the final program. The COM component is then invoked through the RCW. For Microsoft.Office.Interop.Wordd.dll in Office , however, this Assembly is an interop assembly, but it is also the primary interop assembly, the PIA (Primary Interop assemblies). The primary interop assembly is a unique assembly provided by the vendor, and in order to generate the primary interop assembly, you can use the TlbImp command to open the/primary option. Seeing here, my friends must have this question: what is the difference between a PIA and a common assembly? The difference is that the PIA contains some special information, such as the public key, the provider of the COM type library, in addition to the data types defined by the COM component. But why do you need a primary interop assembly? The answer to this question is that--the primary interop assembly helps us to solve the problem of referencing the inconsistent version of the interop assembly when deploying the program. (If the developer generates multiple interop assemblies for a COM component type library, the interop assembly version referenced in the project is inconsistent with the version of the interop assembly at the time of deployment, and when there is an interop assembly, we can directly reference the official supply of the primary interop assembly.) )

Iv. Error Handling

Once you know how to invoke a COM component, you might ask: How do I get the failed message if the method that calls the COM object fails? For this question, the method of handling the error is the same as in our usual managed code, the following is a detailed look at how to get the error message, the following code is the function of-open an existing Word document and insert the corresponding text, when the specified Word document does not exist, In this case, the open method of calling the COM object fails with the following code:

Using system;using microsoft.office.interop.word;using system.io;using system.runtime.interopservices;namespace Error handling in COM Interop {class program {static void Main (string[] args) {//Open existing document insert text St            Ring Wordpath = @ "D:\test.docx";            Openworddocument (Wordpath);        Console.read ();            }//Insert text into an existing document private static void Openworddocument (String wordpath) {//start the Word application            Application WordApp = new application () {Visible = true};            Document Worddoc=null; try {//If the document does not exist, there is a failure to call the COM object//open Word document WordDoc = WORDAPP.D Ocuments.                Open (Wordpath);                Insert text into Word Range WordRange = worddoc.range (0, 0);                Wordrange.text = "This is the inserted text";            Save document Worddoc.save (); } catch (Exception ex) {//Get exception corresponding to HresulT value//Because the HRESULT returned by the method in COM determines whether the invocation succeeded by an int HResult = Marshal.gethrforexception (ex);                Sets the foreground color of the console, which is the color of the output text Console.foregroundcolor = consolecolor.red; The HRESULT value is output Console.WriteLine ("Call throws Exception, exception type: {0}, hresult= 0x{1:x}", ex. GetType ().                Name, HResult); Console.WriteLine ("Exception information is:" + ex.)            Message.replace (' \ R ', ') ');                    } finally {//closes the document and if (WordDoc! = null) {                Worddoc.close ();            }//Quit Word program wordapp.quit (); }        }    }}

If a test.docx document does not exist in our D drive, the code enters the catch block, outputs the exception information, and runs the result:

From the above results we see an HRESULT value, which is really returned in the COM code. In COM, a COM method reports an error by returning an HRESULT , and the. NET method reports an error by throwing an exception, in order to easily get the error and exception information that appears in the COM code in managed code, the CLR provides a conversion between the two. Each HRESULT that represents an error occurs is mapped to an exception class in the. NET framework and can be referenced in the MSDN article for a specific mapping relationship: http://msdn.microsoft.com/zh-cn/library/ 9ZTBC5S1 (vs.80). aspx, I'm not going to use this form to list it specifically. If a HRESULR cannot be mapped to an equivalent. NET Framework Exception class, then it is mapped to the COMException exception class, and we can pass the Marshal class's Gethrforexception method to obtain the HRESULT value corresponding to the exception class (the use of this method has been posted in the code above)

V. Summary

About in. NET calls the COM component's introduction to here, even though we're in. The method of calling COM objects in NET is very simple and convenient, but it is also quite necessary to understand what the CLR does for the work behind us and to understand the principles of calling COM components in managed code. Since we understand the principle of invocation, we can quickly find a solution and solve it when we have a problem, and we will not be able to do so, which will help us to provide the ability to solve the problem.

Go C # Interoperability Primer Series (iv): Calling COM components in C #

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.