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
public interface IExample
void SetText(string text);
public class Example : IExample
private string m_text = “default text”;
public string GetText()
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.
You should get ‘Types registered successfully’.
Your .NET assembly is ready. Now let’s use it.
Open any editor and put the following code:
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:
10. You should see some message boxes.
11. You are done.