C# Interop Tutorial

Creating a .net library for use with a VB6 application can be a tricky thing, but it’s really not that difficult when you follow the correct steps. This article will walk you through the tasks necessary to create an interop class in c# and invoke its methods from a VB6 application.

Create your interface

Just make an interface. Note the ComVisible attribute on the class and the DispId attribute on the methods.

namespace Sample.Vb6Interop
{
    [ComVisible(true)]
    public interface IMyInterop
    {
        [DispId(1)]
        string HelloWorld();
    }
}

Implement the interface in a class

Now implement your interface. Once again, I need to use the ComVisible attribute on the class.

namespace Sample.Vb6Interop
{
    [ComVisible(true)]
    public class MyInterop : IMyInterop
    {
        public string HelloWorld()
        {
            return "Hello, world!";
        }
    }
}

Register the assembly

You’ll use RegAsm to register your DLL. The key to this step is to use the /tlb option to create and register a COM type library. I also use the /codebase option since I’m not installing my DLL in the GAC.

regasm /tlb /codebase Sample.Vb6Interop.dll

Instantiate and use

Now the hard part’s done. In your VB6 project, you can instantiate and use your new class. I use late-binding in my project, but you could also add a reference to your project and use early-binding. (Early-binding is necessary for event handling.)

Private Sub Command1_Click()
    
    Dim objMyInterop As Object
    
    Set objMyInterop = CreateObject("Sample.Vb6Interop.MyInterop")
    
    Call MsgBox(objMyInterop.HelloWorld)
    
End Sub

This will give you a working example, but it only scratches the surface. Things get more complicated quickly when you start talking about events and callbacks.