This is a mirror of official site: http://jasper-net.blogspot.com/

.NET COM interoperation - Fighting with RCW memory leaks

| Tuesday, March 20, 2012
Introduction

Recently I was assigned a task to trace some memory leaks/crashes caused by .NET/COM interop. And I think you will understand what a tough task it is if you have been through it.

After Googling articles, reading them, doing some small trials, I've got some of my own thoughts/understandings. Things that were so daunting to me have now began to makes sense. I want to post them here and share with those who are still struggling.

Background

The general scenario is like this:

We create a COM object using ATL (it's fine if you don't want to utilize ATL and do everything by yourself, but this will be a very tough task). We define those interfaces in IDL files, and we implement them using C++. Then a COM server is done.
We want to use them in .NET. We use tlbimp.exe to generate the RCW (which are actually the generated DLL files).
We begin to consume the COM object by creating the COM object instance and invoking its methods.
The problem we are facing and trying to resolve is:

After the .NET application is done,, some COM objects are not released/disposed/destructed as expected; thus we have memory leaks.
Or/And:

Sometimes we begin to have an exception thrown by the .NET Framework saying "xxx can't be used because the underlying COM object has been separated".
Main Content

Before the exploration starts, I want to stress the fact that always remember there are three layers in case of .NET/COM interoperation: your .NET code, the RCW, and the native COM server. You have full control of your .NET code, but there are lots of rules/disciplines living in the RCW/COM world which you have to understand and follow. Otherwise you'll hit the troubles listed in the above section.

To understand those rules/disciplines in COM & RCW world, I'm going to use some sample code.In this example, I defined 2 COM objects, one is "CQTTest" , representing a test object, the other one is "CQTAction", representing an action object. A test object can contain a lot of action objects, among which there is an active one. Both Test and Action have a method named "Run" (If you have got some experience using Quick Test Professional, you know what i'm talking about). Those idl files and implemementation code are shown as below:

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

0 comments: