C # series of articles on interoperability:
- C # Introduction to interoperability (I): C # Introduction to interoperability
- C # Introduction to interoperability series (II): use the platform to call Win32 Functions
- C # Introduction to interoperability series (III): data sending and processing in Platform calls
- C # Introduction to interoperability series (4): Calling COM components in C #
Summary of this topic:
- Introduction
- How to call COM components in C # -- access office interoperability objects
- Analysis of the implementation principle of calling COM components in C #
- Error Handling
- Summary
I. Introduction
COM (Component Object modele, Component Object Model) is a development technology that Microsoft once admired. Therefore, many Microsoft products now use COM components, such as office and IE. However, what if a program on the. NET platform wants to access the COM component to implement a function? Because developers have this requirement, Microsoft provides support for interoperation between COM and managed code in. NET Framework. This Interoperability Technology isCom InterOP.However, the com InterOP (COM interoperation) technology not only supports using COM objects in managed code, but also supports using Managed Objects in COM. This topic is only. net calls COM objects to introduce, because COM technology is not used much now, so how to use managed objects in COM will not be introduced in this series, if you need a friend can refer to the link msdn: http://msdn.microsoft.com/zh-cn/library/3y76b69k (V = vs.100 ). aspx.
The following describes how to call the COM component in. Net from a specific instance.
2. How to call COM components in C # -- access office interoperability objects
Because office products use many COM components, the following example shows how to create a Word document by calling the COM object in the office and save the created document to the file directory (add it in the newly created console program"Microsoft. Office. InterOP. Word 14.0.0.0"This reference indicates that 14.0.0.0 corresponds to an interoperability assembly in office 2010, and 12.0.0.0 corresponds to the interoperability assembly in Office 2007. If only Office 2007 is installed on your computer, only version 12.0.0.0 can be found. If office 2010 is installed, both versions can be found at the same time .). The Code is as follows:
Using system; // Add additional namespace using Microsoft. office. interOP. word; namespace com interoperability {class program {static void main (string [] ARGs) {// call the COM object to create a Word document createworddocument ();} Private Static void createworddocument () {// start WORD and make word visible application wordapp = new application () {visible = true}; // create a Word document wordapp. documents. add (); document worddoc = wordapp. activedocument; paragraph para = worddoc. paragraphs. add (); para. range. TEXT = "welcome to the learning hard blog"; // Save the Document Object filename = @ "D: \ learninghard.doc"; worddoc. saveas2 (filename); // close word worddoc. close (); wordapp. application. quit ();}}}
The running result is:
Now, you can see the word document you just created in the specified file directory. Through the technology of COM interoperability, We can automate office operations.
Iii. Analysis of the implementation principle of calling COM components in C #
As shown in the preceding example. it is very convenient and simple to call the COM component in. net, so we cannot understand the principle behind it at all, the following describes how to call COM components in managed code and the steps required.
To run the above program, you must add an interoperability assembly --"Microsoft. Office. InterOP. Word 14.0.0.0You can add this Assembly by following the steps below:
- In Solution Explorer, right-clickReference"Folder, and then click"Add reference".
- In". Net"Tab, select the latest versionMicrosoft. Office. InterOP. Word. For example, "Microsoft. Office. InterOP. Excel 14.0.0.0 ". Click OK ".
You can see from the above steps to add a reference,Microsoft. Office. InterOP. Word. dllIt is a. Net assembly, not a COM component. At this time, my friends must have such questions-Didn't they call the COM component? How to call. Net assembly in managed code? How can this be a demonstration of calling COM components under. Net? But the fact is --Microsoft. Office. InterOP. Word. dllIt is indeed.. Net assembly, which is also called the interoperability assembly of COM components. This program contains metadata of the types defined in COM components, managed Code indirectly calls COM objects and interfaces by calling APIs or objects exposed in the interoperability program. Because the hosted Code cannot directly use COM objects and interfaces, the hosted code calls COM objects through CLRCom InterOPThe layer is completed as a proxy. This proxy is RCW (namely, runtime callable wrapper, which can be called for packaging during runtime). Therefore, calls to COM objects are completed through RCW, RCW mainly involves activating COM objects and sending data between hosted code and unmanaged code (from here we can see that RCW is. A proxy between the. NET platform and the COM component. Many Microsoft technologies use proxy, such as the WCF technology. The object we create in code is actually a proxy of the service, access the service of a real object through a proxy object, that is, a method. Speaking of proxy technology, the delegate in C # is also a kind of proxy implementation. At this time, I think of the proxy mode in the design mode in 23, but there are also examples of proxy in my life, rental agencies, proxy Server ). The following figure shows howHow to call COM components in. Net:
About the TLS blmp.exe tool to generate the interoperability Assembly steps, here I will not much detail, you can refer to the msdn tool detailed instructions for use: http://msdn.microsoft.com/zh-cn/library/tt0cf3sx (V = vs.80). aspx.
However, you can also use the built-in support in Visual Studio to create an interoperability Assembly for a com-Type Library.In vs, add a reference to the corresponding COM component for the. NET project. In this case, vs automatically converts the com-Type Library in the com-Type Library to the metadata in the Assembly.And generate the interoperability assembly under the bin directory of the Project. Therefore, add com references to vs. In fact, the interoperability assembly is referenced in the program at the end, then, call the COM component through RCW. However,Microsoft. Office. InterOP. wordd. dll,This Assembly is also an interoperability assembly, but it is also a main interoperability Assembly, namely PIA (primary InterOP assemblies ). The main interoperability assembly is provided by a supplier.UniqueIn order to generate the main interoperability assembly, you can use the tlbimp command to enable the/primary option. My friends may have the question: What is the difference between Pia and common assembly? -- The difference is that Pia not only contains the data types defined by the COM component, but also contains some special information, such as the public key and the provider of the Com-Type Library. But why does it need a master interoperability assembly? The answer to this question is that the main interoperability assembly can help us solve the issue of reference to inconsistent versions of the interoperability Assembly during program deployment. (If developers generate multiple interoperability assemblies for a COM Component Library, the version of the interoperability Assembly referenced in the project is inconsistent with the version of the interoperability Assembly during deployment, with the interoperability Assembly, we can directly reference the primary interoperability Assembly officially provided .)
Iv. Error Handling
After learning how to call the COM component, you may ask: if the method of calling the COM object fails, how can we obtain the failure information? For this question, the error handling method is the same as that in our usual managed code. Let's take a look at how to get the error information, the function of the following code is to open an existing Word document and insert the corresponding text. When the specified Word document does not exist, the open method of the COM object fails to be called, the Code is as follows:
Using system; using Microsoft. office. interOP. word; using system. io; using system. runtime. interopservices; handle errors in namespace com interoperation {class program {static void main (string [] ARGs) {// open an existing document and insert the text string wordpath = @ "D: \ test.docx "; openworddocument (wordpath); console. read () ;}// Insert the text Private Static void openworddocument (string wordpath) to the existing document {// start the word application wordapp = new application () {vis Visible = true}; document worddoc = NULL; try {// if the document does not exist, a failure to call the COM object will occur. // open the Word document worddoc = wordapp. documents. open (wordpath); // Insert the text range wordrange = worddoc to the word. range (0, 0); wordrange. TEXT = "this is the inserted text"; // Save the worddoc. save ();} catch (exception ex) {// obtain the hresult value corresponding to the exception // The Int hresult = successful Al returned by the method in COM. gethrforexception (Ex); // set the foreground color of the console, that is, the color of the output text console. foregroundcol OR = consolecolor. red; // The hresult value is output to the console in hexadecimal notation below. writeline ("the call throws an exception. The exception type is {0}, hresult = 0x {1: x}", Ex. getType (). name, hresult); console. writeline ("exception information:" + ex. message. replace ('\ R', '');} finally {// close the document and if (worddoc! = NULL) {worddoc. Close () ;}// exit wordapp. Quit ();}}}}
If there is no test.docx document in drive D, the Code will enter the Catch Block and output the exception information. The running result is:
From the above result, we can see an hresult value, which is actually returned by com code. In COM, the com method returnsHresultTo report errors ;. the net method reports errors by raising exceptions. to conveniently obtain errors and exception information in the com code in the managed code, CLR provides a conversion between the two, every hresult indicating an error will be mapped. net Framework, for specific ing relationships can refer to the article in msdn: http://msdn.microsoft.com/zh-cn/library/9ztbc5s1 (vs.80 ). aspx. I will not use table columns here. If an hresulr cannot be mapped to an equivalent. NET Framework exception class, it will be mappedComexceptionException class, we can useMarshalClassGethrforexceptionMethod to obtain the hresult value corresponding to the exception class (the usage of this method has been posted in the code above)
V. Summary
For more information about. the introduction of calling COM components in. NET is here, even if we are in. the method to call COM objects in. NET is very simple and convenient, but it is also quite necessary to understand what the CLR is doing behind us and to understand the principle of calling COM components in managed code. After understanding the call principle, we can quickly find a solution and solve the problem when there is a problem, so that we can provide the ability to solve the problem.