Showing posts with label RCW. Show all posts
Showing posts with label RCW. Show all posts

Wednesday, October 18, 2006

Releasing COM components


Clean up after the use of com components ALLWAYS! Don't wait for the garbage collection to take action, free that memory asap. Ensure that the objects are released in a specific order.

To release use the Marshal.FinalReleaseComObject and pass the relevant RCW.

COM uses reference counting to determine when objects finally get released. RCW's cause the underlying COM object to hold onto the reference even when the object variable goes out of scope! The reference will be released only when the GC disposes of the RCW, thus you cannot control when or in what order COM objects are released from memory.

If there are several references held using Marshal.ReleaseComObject will need to be called several times. If you want to release them all in one go then use Marshal.FinalReleaseComObject this will set the reference count straight to zero.
Consume COM components in .NET


If theres a PIA (primary interop assembly) then use it otherwise generate a RCW (tuntime callable wrapper). Use the Type Library Importer (Tlbimp.exe) to do this.

RCW is a special .NET proxy class that sits between the .NET code and the COM component. It handles everything including the marshaling of data types, using COM interfaces and handling COM events.

For using RCW we have the following options:

1. Obtain it from the author of the original COM component. In microsoft offices case the RCW is created from a PIA provided by the publisher.
2. Generate the RCW via Tlbimp.exe or Visual Studio .NET. The later is simple in that we just reference the COM object in the project, the rest is done for you!
3. Create your own manually via types in the System.Runtime.InteropServices namespace. Very tedious and complicated.

Using Tlbimp.exe is simple [ Tlbimp ComComponent.dll ]

Use a PIA where possible, there more likely to work as expected because there created by the original component publisher. They also might include additional .NET refinements or enhancements.

If a PIA is registered for a dll then it will be used in preference to the creation of an RCW when referenced in VS.NET Studio.

Office has a PIA which you can download from http://msdn.microsoft.com/downloads/list/office.asp