Consuming COM Component from .NET



If we want to consume a COM component from a .Net application then first it should be converted into RCW which can done in either of 2 ways:

  1. Using Visual Studio.Net
  2. Using tlbimp utility

1. Using Visual Studio.Net

Open a new project of type windows and name it suppose testcom; now open the Add Reference window and select the COM tab; under it you can find your COM project that might be in vb, vcpp or C++.

After adding a reference you are ready to use the functions, methods and variables in the COM component in your .Net application.

Let's see it with an example; suppose in VB you have a method as and save project name with C# and change the class name to test.

Public function hello() As string
Hello="first hello from com"
End function

Now put a button on a Windows form; follow the above procedure for adding the reference and do as shown in the following:

Csharp.Testclass obj=new Csharp.Testclass obj();
Messagebox.show(obj.hello());

Run the project and test it and then go into the debug folder of the current project where we find the RCW created by VS "Interop.Csharp.dll".

The above RCW that we have created is private which maintains multiple copies if used under multiple projects.
For creating RCW and CCW .Net provides 2 command-line utilities.

Tlbimp (type library importer): used for converting COM component to RCW.

Tlbexp (type library importer): used for converting .Net assembly component to CCW.

2. Using tlbimp Utility

VS is capable of generating RCW of type private only where as tlbimp is capable of generating both private and shared RCW's. It is a command line utility that should be used from a VS command prompt as follows:

Tlbimp(name of com dll)/out:<name of dot net dll>[/Keyfile:<name of key file>]

Creating private RCW

C:\<folder>\VB>tlbimp csharp.dll/out:ComToNetp.dll

Creating Shared RCW

Step1:- Generate key file C:\<folder>\VB>sn –k Key.snk

Step2:-Convert to Shared RCW C:\<folder>\VB>tlbimp csharp.dll/out:ComToNetp.dll/Keyfile:Key.snk

Step3:-Add RCW to Gac C:\<folder>\VB>gacutil –i ComToNets.dll

Now add a reference to the shared RCW created in Step3 from it's physical location.

Now add one button on the Windows form and do the following:

ComToNets. obj=new Csharp.Testclass obj();
Messagebox.show(obj.hello());

Now run the project; we will not see ComToNets.dll in the debug folder as it was shared.


Similar Articles