Memory Management for .NET Components Used by Unmanaged Code
When working in an unmanaged world, we have to make sure that we clean ourselves up if we have allocated memory on the heap (for example, using a keyword new
in C ++); we also need to make sure we are AddRef
COM components created with CreateInstance
and Release
later; maybe 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 similar things (in C ++), but beyond the point ...
Do we also need AddRef/Release
for objects that are captured from COM components (like m_anotherObj in the example above)?
To make things more confusing, what happens if this particular component, which is actually a .NET component, is exposed to unmanaged code via a COM interface? Does the garbage collector know to clean up stuff or does it all have to be done manually in an unmanaged world?
source to share
CreateInstance
will give you an object with reference number 1, so you don't need AddRef
it. (The smart pointer you used will be Release
an object when it is destroyed.) Likewise, the objects you get from methods must have a reference count already incrementing, so you don't need AddRef
them again, but you do need to Release
if you don't use a smart pointer.
COM components introduced by .NET are no different from COM components written by any other technology. The garbage collector will not collect any .NET objects that are referenced by COM references.
source to share