Click here to Skip to main content
15,879,095 members
Articles / Programming Languages / C#
Article

Calling Managed .NET C# COM Objects from Unmanaged C++ Code

Rate me:
Please Sign up or sign in to vote.
4.50/5 (49 votes)
11 Jan 20064 min read 557.1K   7.2K   140   107
An article on calling managed .NET C# COM objects from unmanaged C++ code.

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 with .NET components.

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 a .NET interface doesn't generate any code, and a .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 of .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 the .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 code

Steps 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:
    C#
    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:
    C#
    [ClassInterface(ClassInterfaceType.None)]

Although a .NET class is not directly invokable from unmanaged code, Microsoft has provided the capability of wrapping a .NET interface in an unmanaged layer of code that exposes the methods and properties of the .NET class as if the class were a COM object. There are two requirements for making a .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:
    C#
    [Guid("03AD5D2D-2AFD-439f-8713-A4EC0705B4D9")]
  2. Now, create a GUID for the class, and add the following line for the class:
    C#
    [Guid("0490E147-F2D2-4909-A4B8-3533D2F264D0")]
  3. Your code will look like:
    C#
    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-3533D2F264D0")]
        class MyDotNetClass : IMyDotNetInterface
        {
            // Need a public default constructor for COM Interop.
            public MyDotNetClass()
            {}
            public void ShowCOMDialog()
            {
                System.Windows.Forms.MessageBox.Show("I am a" + 
                      "  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, but .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:

    C#
    [assembly: AssemblyVersion("1.0.0.0")]
  2. Create a strong-name key pair for your assembly and point to it via the AssemblyKeyFile attribute in the AssemblyInfo.cs file which is in your project. Example:
    sn -k TestKeyPair.snk
    C#
    [assembly: AssemblyKeyFile("TestKeyPair.snk")]
  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 your DoNet_COM_Call.cpp file:
    #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 should 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Atul Mani Tripathi has been a professional developer since 1997 and working as a senior consultant with Cognizant Technology Solutions (CTS) .

Most of the time, his focus is on creating a clean and simple solution to development problems. He is a C++, Visual C++ and C# (Dot NET) guy who loves Visual Studio, Google, Code Project and developing personal projects.


Comments and Discussions

 
GeneralRe: Correction Pin
voorugonda prashanth8-Apr-07 20:56
voorugonda prashanth8-Apr-07 20:56 
GeneralCalling back to Unmanaged C++ code Pin
rschmidtatirrs17-Apr-06 8:03
rschmidtatirrs17-Apr-06 8:03 
GeneralNet control as ActiveX control Pin
Beloff_P1-Apr-06 1:35
Beloff_P1-Apr-06 1:35 
QuestionUsing .NET functionality Pin
srappold30-Mar-06 8:03
srappold30-Mar-06 8:03 
AnswerRe: Using .NET functionality Pin
sephres18-Oct-06 4:01
sephres18-Oct-06 4:01 
GeneralRe: Using .NET functionality Pin
sraap19724-May-07 1:59
sraap19724-May-07 1:59 
QuestionHow to do in events? Pin
RobertChan200029-Mar-06 22:23
RobertChan200029-Mar-06 22:23 
QuestionExporting c# class that resides inside a .NET executable Pin
aviv7322-Mar-06 7:21
aviv7322-Mar-06 7:21 
Hi Atul,

I wanted to ask if it's possible to use the method you described to export a class that is instantiated inside a running C# program.

What I need is to access a .NET queue object that is defined in a running C# application.
If I'll use COM interop will the queue be generated under the calling C++ process, or will it communicate with the object running under the .NET application?

Thanks,

Aviv Scharf
GeneralTrouble with Compiling the console app Pin
Sphyrix15-Mar-06 5:35
Sphyrix15-Mar-06 5:35 
GeneralRe: Trouble with Compiling the console app Pin
sajal22-Sep-06 5:05
sajal22-Sep-06 5:05 
GeneralRe: Trouble with Compiling the console app Pin
time_error10-Dec-06 20:36
time_error10-Dec-06 20:36 
GeneralRe: Trouble with Compiling the console app Pin
dandolo9-Feb-07 1:56
dandolo9-Feb-07 1:56 
GeneralUsing your example Pin
AlexEvans12-Jan-06 21:02
AlexEvans12-Jan-06 21:02 
GeneralRe: Using your example Pin
Atul Mani12-Jan-06 22:21
Atul Mani12-Jan-06 22:21 
GeneralRe: Using your example Pin
AlexEvans12-Jan-06 22:52
AlexEvans12-Jan-06 22:52 
GeneralRe: Using your example Pin
Atul Mani12-Jan-06 23:57
Atul Mani12-Jan-06 23:57 
GeneralRe: Using your example Pin
AlexEvans13-Jan-06 19:54
AlexEvans13-Jan-06 19:54 
GeneralRe: Using your example [modified] Pin
Jason C Daniels7-Sep-06 3:42
Jason C Daniels7-Sep-06 3:42 
GeneralWizard for easy COM class creation Pin
mav.northwind11-Jan-06 6:24
mav.northwind11-Jan-06 6:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.