Sunday, February 14, 2010

Register .net assembly as COM


Introduction
We have used VB6.0 DLL or OCX component in our .Net application. But sometime we need to use our .Net DLL into VB6.

In the following scenario you need to use .Net DLL into VB6.
  • Any third party module is available in .Net and you need to integrate it with your VB6.0 application

  • Your some modules are already developed into .Net and you have to integrate it with VB6.0 application


This blow will explain you how to create COM compatible .Net assembly step by step.

First we need to create one class library project. Open Visual Studio and create new Class Library project. Give “DemoClassLibrary1” name to your class library.

Create new class which needs to be expose as a COM object. Just add new class into your class library project. Give “DemoClass1” to your class name.


Public Class DemoClass1

Public Function GetWelcomeString(ByVal name As String) As String
GetWelcomeString = "Welcome " + name
End Function

End Class

Now to create it COM compatible, you have to add ComClass attribute on your class definition. So updated code will look like below:



Public Class DemoClass1

Public Function GetWelcomeString(ByVal name As String) As String
GetWelcomeString = "Welcome " + name
End Function

End Class

I have created one method which will be exposed as a COM method.

You also need to set your project as a Com compatible. To configure it, open project property. Right click on project in solution explorer and select properties option. In compile tab, select checkbox “Register for COM Interop”.

Now when you will build your project, project will create DLL as well as TLB file. This TLB file needs to use your .Net DLL into VB6.

Let’s use this DLL into VB6. Open your VB6 project and open reference dialog to add your .Net class reference. You will get option for “DemoApplication1”, select the option and click on ok.

Now you can create object of “DemoClass1” and use your function “GetWelcomeString”.

If you want to use this component on another machine then you have to copy the DLL file on that machine and register your DLL file to the registry so your VB6 application can find your component.

To register the component, Open Visual Studio 2008 command prompt and execute following command.


Regasm <<DLL file full path>> /tlb:<<tlbfilename>> /codebase

Regasm command generate TLB file and also register it with the system. Codebase option also set the code base with the registry.

No comments:

Post a Comment

DotNet Code Guru