-1

iam not used to COM but i needed to create a .NET component using C# to be compiled as a dll to be used in another program suite, so i did it as a COM object (registering for COM interop, and the assembly visible to COM etc..)

Assuming that i have my interface class:

using System.Runtime.InteropServices;

namespace Test
{
 public interface IFoo
 {
  void method1(parameter1);
  void method2 (parameter2);
 }
 [ComVisible(true),ClassInterface(ClassInterfaceType.None)]
 public class myname : IFoo
 {
   FooClass class;
   public myname()//Constructor
   {
   }
   public void method1(parameter1)
   {
     class = new FooClass();
     class.Method1(parameter1);
    }
 }
}

After this i compile it and register the dll on another computer using regasm. I run it, but this application consume lots of memory and never frees itself, does anyone knows a way to release it/destroy it?

Question is how to release memry usage? thanks in advance

WickedJenn
  • 43
  • 1
  • 7

1 Answers1

1

Calling .NET through COM, the memory leaks usually happen at the COM Callable Wrapper layer.

When a COM client calls a .NET object, the common language runtime creates the managed object and a COM callable wrapper (CCW) for the object. Unable to reference a .NET object directly, COM clients use the CCW as a proxy for the managed object.

The CCW is reference-counted in traditional COM fashion. When the reference count on the CCW reaches zero, the wrapper releases its reference on the managed object. A managed object with no remaining references is collected during the next garbage-collection cycle. So if the reference count of a object is not reduced to 0, there's a leak

Recently I also deal with the same cases, based on my experience, you should:

  1. Check if you're using the COM smart pointer type in your native code. When you use #import xxx.tlb, the compiler creates the code like this:

    _COM_SMARTPTR_TYPEDEF(IFoo, __uuidof(IFoo));

    when you use IFoo interface in your C++ code, you should use IFooPtr, this is a COM smart pointer type, which will call the Release() function when the variable is out of scope.

  2. The usage of SAFEARRAY. When you return an array from C#, it will be returned as a SAFEARRAY * type to C++, you have to call SafeArrayDestory() on that safe array to free the memory.

The tool I used is DebugDiag. It is from Microsoft and free, and also powerful.

Matt
  • 6,010
  • 25
  • 36