Friday, July 22, 2005

How to expose COM objects to .NET Framework

To expose COM to NET, we will make a "Wrapper", or "Proxy Assembly", which plays the role of the bridge between the COM object and the .NET applications. This assembly will be put into the /bin sub folder once generated.

To generate this Wrapper Assembly, we will need to run a program called tlbimp.exe, which comes with the .NET Framework. The command line takes a Type Library as the parameter and optionally a output assembly name as another parameter:

tlbimp foo.tbl /out:myfoo.dll

Once the assembly myfoo.dll is generated, it will be placed in the /bin sub folder.
After this, using COM is just like using any other assembly. For example, in VB.NET, the code is like:

Import myfoo

Dim foo as new myfooClass

foo.method1.....
foo.method2....
foo.method3....

The next issue is how to get the type library. Type Library can be a standalone file with the extension of .tlb, or is embedded in the COM dll files, or in ocx, or olb files. If it is embedded into a dll, then the tlbimp command line will be like:

tlbimp foo.dll /out:myfoo.dll (please be careful not to override the original dll, by specifying a different sub folder in /out:, if you want to use the same name as the output.)

If you are using VS.NET, then creating the COM wrapper is as easy as adding an reference. No TlbImp command needed:

To add a reference to a type library

Install the COM DLL or EXE file on your computer, unless a Windows Setup.exe performs the installation for you.
From the Project menu, select References.
Select the COM tab.
Select the type library from the Available References list, or browse for the TLB file.
Click OK.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home