C # develop COM component instances (with source code)

Source: Internet
Author: User
Tags dotnet
ArticleDirectory
    • . Net interfaces and Classes
    • Steps to create a managed. Net C # COM Object:
    • Requirement 1:
    • Requirement 2:
    • Steps to create an unmanaged C ++ application to call a. Net managed C # com
Preface

Com interoperability is the feature of Microsoft. NET that allows managed. Net code to interact with unmanaged code using Microsoft's component object model semantics.

This article is geared towards C # programmers who are familiar with Developing COM components and familiar with the concept of an interface. i'll review some background on com, explain how C # interacts with COM, and then show how to design. NET components to smoothly interact with COM.

For those die-hard com experts, there will be some things in this article that are oversimplified, but the concepts, as presented, are the important points to know for those developers supplementing their com code. NET components.

Source code: Download

Introduction. Net interfaces and Classes

the basis for accessing. net objects either from other. net code or from unmanaged code is the class. a. net class represents the encapsulation of the functionality (methods and properties) that the programmer wants to expose to other code. a. net interface is the abstract Declaration of the methods and properties that classes which implement the interface are expected to provide in their implementations. declaring. net interface doesn' t generate any code, and. net interface is not callable directly. but any class which implements ("inherits") the interface must provide the code that implements each of the methods and properties declared in the interface definition.

Microsoft realized that the very first version. net needed a way to work with the existing Windows technology used to develop applications over the past 8 + years: COM. with that in mind, Microsoft added support in. net runtime for interoperating with com-simply called "com InterOP ". the support goes both ways :. net code can call COM components, and COM code can call. NET components.

Using the codesteps to create a managed. Net C # COM Object:
    1. open vs. net2003-> new project-> Visual C # projects-> class library.
    2. Project name: myinterop.
    3. Create mydonetclass. CS file, and add the following lines of code:
        using  system. runtime. interopservices;  using  system. windows. forms; 
    4. Create an interface imydotnetinterface .
    5. Create a class mydonetclass .
    6. Add the following line for mydotnetclass :
       [classinterface (classinterfacetype. none)] 

Although. net class is not directly invokable from unmanaged code, Microsoft has provided the capability of wrapping. net interface in an unmanaged layer of code that exposes the methods and properties of. net class as if the class were a COM object. there are two requirements for making. net class visible to unmanaged code as a COM Object:

Requirement 1: You have to add guids-globally unique identifiers-into your code for the interface and the class separately, through a guid tool.

  1. Now, create a guid for the interface, and add the following line for the interface:

    [GUID (<SPAN class = "code-string"> "</span> <SPAN class =" code-string "> 03ad5d2d-2afd-439f-8713-a4ec0705b4d9" </span>)]
  2. Now, create a guid for the class, and add the following line for the class:
    [GUID (<SPAN class = "code-string"> "</span> <SPAN class =" code-string "> 0490e147-f2d2-4909-a4b8-3533d2f1_d0" </span>)]
  3. Your code will look like: Collapse
     Using System; Using System. runtime. interopservices; Using System. Windows. forms; Namespace Myinterop {[GUID ( " 03ad5d2d-2afd-439f-8713-a4ec0705b4d9" )] Interface Imydotnetinterface { Void Showcomdialog ();} [classinterface (classinterfacetype. None)] [GUID ( "  0490e147-f2d2-4909-a4b8-3533d2f1_d0" )] Class Mydotnetclass: imydotnetinterface { //  Need a public default constructor for com InterOP.          Public Mydotnetclass (){} Public   Void Showcomdialog () {system. Windows. Forms. MessageBox. Show ("I Am "  +" Managed dotnet c # com Object Dialog ");}}}
  4. Compile the solution.
  5. You will see inside the project directory-> obj-> DEBUG directory, the file"Myinterop. dll"Generated after compilation.
Requirement 2: registration of the COM class and interfaces

For a com class to be accessible by the client at runtime, the com infrastructure must know how to locate the code that implements the com class. com doesn' t know about. net classes,. NET provides a general "surrogate" DLL-Mscoree. dll-- Which acts as the wrapper and intermediary between the COM Client and the. NET class.

  1. hard-code a specific version number in your assemblyversion attribute in the assemblyinfo. CS file which is in your project.

    example:

     [assembly: assemblyversion ( "  1.0.0.0" )] 
  2. Create a strong-name key pair for your assembly and point to it viaAssemblykeyfileAttribute inAssemblyinfo. CSFile which is in your project. Example:
    Sn-K testkeypair. SNK
    [Assembly: assemblykeyfile (<SPAN class = "code-string"> "</span> <SPAN class =" code-string "> testkeypair. SNK" </span>)]
  3. Add your assembly to the GAC using the following command:
    Gacutil/I myinterop. dll
  4. Register your Assembly for com by using the regasm command along with the "/TLB" option to generate a com Type Library.
    Regasm myinterop. dll/TLB: COM. myinterop. TLB
  5. Close the C # project.
Steps to create an unmanaged C ++ application to call a. Net managed C # com
  1. Open vs. net2003-> new project-> visual c ++ projects-> Win32-> Win32 console project.
  2. Name: dotnet_com_call.
  3. Include the following line in yourDonet_com_call.cppFile:
    # Import"<Full path>\ Com. myinterop. TLB"Named_guids raw_interfaces_only
  4. Compile the solution.
  5. It will generate a"Com. myinterop. tlh"File into your project-> DEBUG directory.
  6. You can open this file and see the contents. This is basically the proxy code of the C # com code.
  7. Now, you can write the code to call the. NET managed COM.
  8. Please add the following lines of code before calling the com exported functions:
    Coinitialize (null ); //  Initialize all COM components      //  <Namespace >:: <interfacename> Myinterop: imydotnetinterfaceptr pdotnetcomptr; //  Createinstance Parameters //  E.g. createinstance (<namespace: CLSID _ <classname>) Hresult hres = pdotnetcomptr. createinstance (myinterop: clsid_mydotnetclass ); If (Hres = s_ OK) {BSTR STR; pdotnetcomptr- > Showcomdialog (); //  Call. Net com exported function showdialog () } Couninitialize (); //  Deinitialize all COM components 
  9. Run this console application.
  10. Expected result: a managed code (C #) dialog shoshould appear with the string "I Am a managed DOTNET C # COM Object dialog ".
Points of interest

While creating an interface for com exported functions, creating guids for the interface and the class and registering the class are required steps, and doing all this is always interesting and fun. calling parameterized exported functions also is very interesting.

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.