I have a C# class that I've made ComVisible so that开发者_运维知识库 it can be used in an unmanaged C++ DLL. The C# class is defined like this:
public interface IFSFunction
{
double GetProcessTime();
}
public class Functions : IFSFunction
{
// Initialization here
// Interface function
public double GetProcessTime()
{
// Do stuff - return a value
}
}
Then, in my C++ DLL I get a reference to the C# class like this:
IFSFunctionPtr pIFuncs;
pIFuncs.CreateInstance(__uuidof(Functions));
double proctime = pIFuncs->GetProcessTime()
pIFuncs.Detach()->Release();
This calls the C# functions very nicely, but it doesn't seem to clean up correctly afterwords. There still seems to be a reference to my C# class hanging around. How can I make sure that my C# COM object is completely gone?
I'm going to guess you are using a debugging tool that let's you take a look at the managed heap. Like Windbug.exe with sos.dll. Yes, you'll see an instance of the Functions class object after the final Release() call. It is a managed object that follows normal garbage collection rules. It won't be collected until the garbage collector runs. It will be, as long as you keep running managed code that allocates memory.
Does this work for you? (sorry, it's C# rather than C++)
try
{
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(pIFuncs);
}
catch (System.Exception ex)
{
// Do nothing
}
finally
{
pIFuncs = null;
}
Info on Marshal.FinalReleaseComObject
here.
精彩评论