Memory management for .NET components used by unmanaged code
-
08-07-2019 - |
Question
When working in the unmanaged world, we have to make sure that we clean up after ourselves if we have allocated memory on the heap (e.g. by using the new
keyword in C++); we also have to make sure that we AddRef
COM components that are created using CreateInstance
and to Release
it later; perhaps something like:
SomeNameSapce::IObjPtr obj;
HRESULT hr = obj.CreateInstance(L"SomeObject");
if (hr == S_OK)
{
obj->AddRef();
m_anotherObj= obj->GetObj();
obj->Release();
}
Obviously we could use smart pointers and other such things (in C++) but that's besides the point...
Do we also have to AddRef/Release
for objects that are grabbed from COM components (like m_anotherObj in the example above)?
To make things more confusing, what happens if this particular component that is actually a .NET component which is being exposed to unmanaged code via a COM interface? Does the garbage collector know to clear stuff up or does it all have to be done manually in the unmanaged world?
Solution
CreateInstance
will give you back an object with a reference count of 1, so you do not need to AddRef
it. (The smart pointer you have used will Release
the object when it is destroyed.) Similarly, objects you receive from methods should have the reference count already incremented, so you do not need to AddRef
them again - but you do need to Release
them, unless you are using a smart pointer.
COM components exposed by .NET are no different from COM components written by any other technology. The garbage collector will not collect any .NET objects referenced from COM references.