Dear Blog:

Well, if you had read my story The Vendor From Hell on The Daily WTF you will know what's been keeping me busy.

The long and short of it is that I had to write code to print to a specialty printer, and I had to provide an API to that code to our software vendor so that my print library could be integrated into the software we use.

More on the code later.

So I decide, since I have no confidence that the vendor will be able to integrade my C# library with their VB6 software I should write a sample VB project for them with the functionality all in there.  Now that was an exercise in itself since I haven't written VB6 in about 3 years.  The IDE was bitching at me non-stop about semicolons and curly braces, and I could not for the life of me put a FOR loop together...

But to the point, exposing a C# assembly to be used in VB as a COM object is pretty easy once you know what you are doing.  I think there are more ways than this to do it, but here's what I did.

    1 [System.Runtime.InteropServices.GuidAttribute("D02C57A7-B7E0-459f-987F-289FEF1B241F")]
2 [System.Runtime.InteropServices.ClassInterface(
System.Runtime.InteropServices.ClassInterfaceType.AutoDual)]
3 public class Foo
4 {
5 private int bar;
6 private string baz;
7
8 public Foo()
9 {
10 //do stuff
11 }
12 public string SomeMethodToCall()
13 {
14
15 }
16 public int Bar
17 {
18 get{return(bar);}
19 set{bar = value;}
20 }
21 public string Baz
22 {
23 get{return(baz);}
24 set{baz = value;}
25 }
26 }

 

Line 1 sets a GuidAttribute on the class.  A registered component needs a GUID to identify it to the system.  Simply use the GUID generator in the Visual Studio IDE (from the TOOLS menu) and paste it into the attribute.

Line 2 Sets the Interface so that it supports VB early and late binding.  This is important because this attribute is what makes VB's Intellisense recognize the object.

The constructor is at line 8.  The unfortunate thing is that, to my knowledge, VB does not support instantiating an object with parameterized constructor.  So you have to provide the default constructor, and then any variables that you need set need to be exposed as public properties in the class.  VB then can interact with the properties and methods of the class as normal.

The next step is to register your component.  Do this by opening the VS.NET command line and travelling to the directory where the dll lives.  The command is regasm /tlb:myComponent.tlb myComponent.dll

Once you have run regasm, you are golden.  Fire up VB and in the Project | References menu, your TLB will show up and you can interact with it.

Hope this helps someone!

 

Now playing: Sponge - Molly


Tags: