David
David

Reputation: 5537

How does a C# DLL marked for COM interop work in a vb6 application

I have a simple C# library that I have registered for COM interop. I have added a reference for this to my vb6 app. I ran my vb application and everything works fine. What I would like to know is how does this work. I checked the task mamager and I see VB6.exe in the processes but I cannot see anything relating to .net.

code: vb6

Dim a As CsharpdllForVBHack.ComAdder
Private Sub Command1_Click()
    Set a = New CsharpdllForVBHack.ComAdder
    a.Add 1, 4
End Sub

code: C#.net

 [ComVisible(true)]
 public class ComAdder
 {
    [ComVisible(true)]
    public void add (int a,int b)
    {
        TestForm testForm = new TestForm(a+b);
        testForm.ShowDialog();
    }
 }

I would also like to know how would I handle disposing of this com object once I am done

We noticed that each time we click on the button and close the form the memory used goes up by a few 100 kb even adding set a= Nothing

Upvotes: 0

Views: 1853

Answers (2)

Mark Bertenshaw
Mark Bertenshaw

Reputation: 5689

In your case, VB instantiates a COM Callable wrapper class (CCW) which lives inside the .NET assembly. The usual COM-type things happen here. First of all, COM looks up the GUID for the class in the registry, and finds the assembly DLL, which it loads into the process of the VB component. COM tries to find a function which retrieves a pointer to a standard COM interface, which you use to instantiate the COM class. You now have a COM object.

But that is not the whole story. When you instantiate the CCW, it also ensures that the .NET runtime is loaded, and then creates an instance of the .NET class. Your COM object has an interface which is based on the .NET interface. The CCW essentially forwards all calls from the COM interface to the .NET interface, converting the COM data types to .NET data types, and back again if you have return values and out parameters.

As for your second point - in this particular case, don't bother. When VB gets to the end of the procedure (or Exit Sub, or raises an error), it jumps to a subroutine which clears down all procedure level variables. If object variables are cleared, the reference count to the COM object is decremented. If the reference count is zero, the COM instance kills itself.

In your case, when the COM class kills itself, it takes extreme measures to ensure that the .NET object is destroyed, but you cannot rely on this behaviour, as with all .NET objects.

Upvotes: 5

Matt Wilko
Matt Wilko

Reputation: 27322

The first part of your question is too broad to be answered here have a look at COM Interop for much more information on this subject.

The second part of your question is answered as follows:

To dispose of the object in VB6 you do the following:

Set a = Nothing

Making sure there are no other references left around.

Upvotes: 3

Related Questions