COM and .Net interoperability
Published: 21 May 2002 15:18 BST
Interoperability without Visual Studio.Net
Suppose you are not using Visual Studio.Net. Another way of achieving the same result is to use the .Net Framework tool called the Type Library Importer (tlbimp.exe). This tool can be used to convert type definitions in a COM library into a .Net assembly.
For example, if you have a COM DLL named MyCOMComponent.dll, you can build an RCW for it as follows:
Tlbimp MyCOMComponent.dll /out:MyRCW.dll
In the case of ActiveX Controls, you can use the .Net Framework tool called the ActiveX Importer to convert the type definitions in an ActiveX Control into a Windows Forms Control. It can be used from the command line as follows:
Aximp MyOCX.ocx
Wrap it up
If you are wondering how Visual Studio.Net or the command-line tools generate these wrappers, here is the key. The .Net Framework Class Library has a class called TypeLibConverter (System.Runtime.IneropServices.TypeLibConverter), which exposes a method called ConvertTypeLibToAssembly that can be used to write your own tool; this tool generates an RCW. The same is true for the ActiveX controls -- the AxImporter Class (System.Windows.Forms.Design.AxImporter) can be used to generate RCWs for ActiveX controls.
Memory management
One of the main architectural differences between .Net and COM is memory management. The CLR provides automatic memory management by means of a garbage collector that manages the allocation and release of memory. This is done periodically, so an object is not immediately destroyed when it goes out of scope or when it is set to Nothing (Visual Basic.Net, the same as null in C#).
When an RCW goes out of scope or is set to Nothing, the object is not destroyed immediately, and the corresponding COM object will also reside in memory -- which might not be desirable. In such situations, steps should be taken to clean up the memory. You can do so by calling the garbage collector, by calling the System.GC.Collect method, or -- the preferred way -- by calling the Marshal.ReleaseComObject method on the RCW.
Conclusion
It is heartening that code that exists as COM objects can still be used from the .Net Framework, thanks to wrapper classes that act as bridges between the two platforms. With tools like Visual Studio.Net, the process has been made simple and almost transparent to the user. So, the next time you remember that you have a COM object that implements the functionality you need while developing in .Net, consider the option of COM Interop. In the next part of this series, we'll look at utilising .Net assemblies from COM.
Have your say instantly in the Tech Update forum.
Find out what's where in the new Tech Update with our Guided Tour.
Let the editors know what you think in the Mailroom.









