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.