C#
namespace TestController
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IController {
void DoSomething();
}
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
public class ControllerImpl : IController {
public void DoSomething()
{
throw new NotImplementedException();
}
}
}
C++
#import "c:\prj\Controller\bin\Debug\TestContro开发者_运维问答ller.tlb"
using namespace TestController;
int _tmain(int argc, _TCHAR* argv[])
{
IControllerPtr ctrl;
CoInitializeEx(NULL, COINIT_MULTITHREADED);
while (true) {
HRESULT hr = ctrl.CreateInstance(__uuidof(ControllerImpl));
ctrl = 0;
}
return 0;
}
Hi all,
I need to provide access to my .NET class library from unmanaged code. Beeing totally new to the subject, I spent several days studying the COM / interop, then defined and implemented a COM accessible interface, made a test run and everything just worked, until I noticed something that seemed as a memory leak. I isolated the offending statements, but still have no clue why is the above code broken.This is probably a case of:
http://jpassing.com/2009/03/26/rcw-reference-counting-rules-com-reference-counting-rules/
Specifically, .NET uses RCW reference counting rules, which are different to the usual reference counting rules in COM applications.
This results in apparent leaks until the .NET RCW reference counting observes that a given object is no-longer used, and this requires cooperation from its garbage collector.
精彩评论