Exposing your .NET assembly through COM

I wanted to write a simple .NET assembly, make some of the methods exposed through COM and use these methods in another program. It sounded so simple that I thought I will be done in an hour. It took me two days to figure out how to do this. Blame me on my poor googling skills, but the information was so scattered that I felt bad for my fellow programmers who might spend the same amount of time looking for a solution. So I have decided to put up an example here so that it saves time for others.

Let’s first write the application which we want to expose through COM. We will define an interface (not mandatory, you can do away with the interface) and put in all the methods which should be exposed through COM. Then, we will write the class which will implement this interface. There are three things extra we need to do to make our application COM compatible.

i. Create a GUID and it add as an attribute for the interface.
ii. Create a GUID and it add as an attribute for the class.
iii. Add the Comvisible(true) attribute to all the functions you want to expose through COM.

So, here is the step by step detail.

1. Create a class library project in Visual Studio. Name it ComExample.
2. Copy and paste the code below into Class1.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ComExample
{
[Guid(“77699130-7D58-4d29-BE18-385871B000D1”)]
public interface IExample
{
string GetText();
void SetText(string text);
}

[Guid(“F91E5EE1-D220-43b5-90D1-A48E81C478B7”)]
[ComVisible(true)]
public class Example : IExample
{
private string m_text = “default text”;

public string GetText()
{
return m_text;
}

public void SetText(string text)
{
m_text = text;
}

}
}

3. Open the project properties page.
3a.Under the Build tab, check the box ‘Register for COM interop’
3b. Under the Signing tab, check the box ‘Sign the assembly’, click on the <New…> in the drop down box,
give a name to your key file and save it. This file will be automatically added to your project.

4. Build the project. You should have a dll named ComExample.dll
5. Open Visual Studio Command prompt and go to the directory where the dll is stored.
6. Type in the following command.

gacutil -i ComExample.dll

The response should be: “Assembly successfully added to the cache”

7. Type in the following command.

regasm ComExample.dll

You should get ‘Types registered successfully’.

Your .NET assembly is ready. Now let’s use it.

Open any editor and put the following code:

Dim object

set object = CreateObject(“ComExample.Example”)
MsgBox(“Created the object.”)

defaultText = object.GetText()
MsgBox(“Default text : ” & defaultText)

object.SetText(“My new text”)
newText = object.GetText()

MsgBox(“New text is ” & newText)

8. Save it as use_com.vbs.
9. From the command prompt, type the command:
cscript use_com.vbs

10. You should see some message boxes.

11. You are done.

Advertisements

14 thoughts on “Exposing your .NET assembly through COM

  1. Joe Krueger says:

    That is all well and good for running on your development server but how do you expose the dll to COM on another machine that doesn’t have visual studio installed on it???

    Thanks!

  2. anaamica says:

    Joe, to expose this assembly on any machine, you need to have atleast .NET framework installed. Registering the DLL, signing it and adding it to gac can be done using .NET tools, sometimes on the command prompt itself. So, Visual Studio is not a must, but yes you do need .NET framework.

  3. Romilton S. says:

    Yes it works but is it possible to have an intellisense for the class if you use the it in vb6? Because it is hard for my programmers if my assembly class consists of many methods and properties.

  4. The next time I read a web site, I hope that it doesnt disappoint me as very much as this a single. I mean, I know it was my choice to read, but I truly believed youd have one thing intriguing to say. All I hear can be a bunch of whining about something that you just could fix should you werent too busy searching for attention.

  5. Martin says:

    Perfect proof of concept for me. Thanks a bunch!

  6. xaufad says:

    Great Job Mr. Generous…

  7. merwan says:

    I followed same procedure. But i got this error:
    Microsoft VBScript Compilation error: Invalid character
    at line 4, 27

    Dim object

    set object = CreateObject(“ExposeToCom.UseIExpose”)
    MsgBox(“Created the object.”)

    defaultText = object.GetDay()
    MsgBox(“Default text : ” & defaultText)

  8. merwan says:

    namespace ExposeToCom
    {

    [Guid(“BAD5EC74-C3D9-4E03-AD2C-25DFAFE6E4B2”)]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IExpose
    {
    [DispId(1)]
    int GetDay();
    }

    [Guid(“60125B42-23D3-4334-9AEE-4ADB43E3808F”)]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId(“ExposeToCom.UseIExpose”)]
    [ComVisible(true)]
    public class UseIExpose:IExpose
    {

    public int GetDay()
    {
    return (DateTime.Today.Day);
    }
    }
    }

  9. Kevin Olson says:

    I know it’s been awhile since this was last looked at, but I just stumbled onto this site. We’re running into a problem where we have a pricing program written in MS Access (don’t laugh TOO hard). We need to make it Office 64 bit compatible. It has a pretty important treeview control from MSCOMCTL. I’m really unfamiliar with how to make a .NET control wrap into a COM control.

    Can anyone help me figure out how to wrap a .NET treeview control into a COM control that we can use in our MS Access program?

  10. Luis says:

    Amazing! Its really amazing article, I have got much clear idea concerning from
    this piece of writing.

  11. Valuable info. Lucky me I found your site accidentally, and I’m surprised why this coincidence didn’t came about
    earlier! I bookmarked it.

  12. Thank you a bunch for sharing this with all folks you really recognize what you’re talking approximately! Bookmarked. Kindly also seek advice from my web site =). We can have a hyperlink alternate contract between us

  13. Michal says:

    It seems like u really fully understand quite a lot
    about this subject matter and that exhibits with this particular posting,
    given the name “Exposing your .NET assembly through COM | Codelicious”.
    Thanks a lot ,Louis

  14. I have read so many posts on the topic of the blogger lovers however this piece
    of writing is in fact a good post, keep it up.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: