Turn a simple C# DLL into a COM interop component

Elena Lawrence picture Elena Lawrence · Aug 17, 2011 · Viewed 86.8k times · Source

How do I make a C# DLL into a COM interop DLL that can be consumed by a VB6 application?

Answer

Kieren Johnstone picture Kieren Johnstone · Aug 17, 2011

This is the answer I wanted to find in StackOverflow but couldn't. It turns out to be fairly easy to turn a simple C# dll into a COM dll.

To create the C# dll

Create a solution with a C# class project. The class should have an interface for the properties/methods and an interface for the events. Assign GUID attributes to the class and interfaces as described in MSDN - Example COM Class (C# Programming Guide). Also see: MSDN - How to: Raise Events Handled by a COM Sink.

In Project Properties > Application tab > Assembly Information button > check "Make assembly COM-Visible". This makes all public methods in the class COM visible.

In Project Properties > Build tab > Set "Platform target" to x86.

That's all you need to do to create the DLL. To call the DLL, you need to register it.

Registering the DLL on your development machine

You can register the DLL one of these ways:

  • Check Project Properties > Build Tab > "Register for COM Interop". This will automatically register the DLL when you build it.
  • Manually register the DLL with RegAsm. This allows you to register the DLL in the directory of your choice, rather than in the build directory. This is the method I used.

    • Do not check Project Properties > Build Tab > "Register for COM Interop"
    • Copy the DLL to the directory where you want to register it
    • Open a command shell with administrator rights and type

      RegAsm.exe -tlb -codebase mydll.dll
      

      RegAsm.exe can be found in "C:\Windows\Microsoft.NET\Framework\v2.0.50727", while "mydll.dll" is the name of your DLL; tlb means "create a type library"; codebase means "write the directory location to the Registry, assuming it is not being placed in the GAC".

      RegAsm will display a warning that the assembly should be strong-named. You can ignore it.

      At this point, you should be able to add a reference to the COM DLL in VB6, see it with Intellisense, and run it just like a regular COM DLL.

Installing the DLL with InstallShield

If you are using InstallShield to install the DLL along with the rest of your application, do the following.

In InstallShield, add a new Component to the Components list. Remember to associate the Component with a Feature. Set component property ".NET COM Interop" to Yes.

Add the .dll file to the Files section of the Component. Do not check the "Self-Register" property. Right-click on the .dll file and select "Set Key File".

Add the .tlb file to the Files section of the Component. Check the "Self-Register" property.

The correct version of the .Net Framework needs to exist on the target PC.

That's it.