非托管代码使用的.NET组件的内存管理

时间:2022-10-01 21:01:44

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:

在非托管世界中工作时,如果我们在堆上分配内存(例如在C ++中使用new关键字),我们必须确保我们自己清理;我们还必须确保使用CreateInstance创建AddRef COM组件并稍后将其释放;也许是这样的:

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...

显然我们可以使用智能指针和其他类似的东西(在C ++中),但除此之外......

Do we also have to AddRef/Release for objects that are grabbed from COM components (like m_anotherObj in the example above)?

对于从COM组件中获取的对象(如上例中的m_anotherObj),我们还需要AddRef / Release吗?

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?

为了让事情更加混乱,如果这个特定的组件实际上是一个通过COM接口暴露给非托管代码的.NET组件会发生什么?垃圾收集器是否知道清除内容或者是否必须在非托管环境中手动完成?

1 个解决方案

#1


1  

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.

CreateInstance将返回一个引用计数为1的对象,因此您不需要AddRef它。 (您使用的智能指针将在销毁时释放对象。)同样,从方法接收的对象应该已经增加了引用计数,因此您不需要再次添加它们 - 但是您需要释放它们,除非你使用智能指针。

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.

.NET公开的COM组件与任何其他技术编写的COM组件没有什么不同。垃圾收集器不会收集从COM引用引用的任何.NET对象。

#1


1  

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.

CreateInstance将返回一个引用计数为1的对象,因此您不需要AddRef它。 (您使用的智能指针将在销毁时释放对象。)同样,从方法接收的对象应该已经增加了引用计数,因此您不需要再次添加它们 - 但是您需要释放它们,除非你使用智能指针。

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.

.NET公开的COM组件与任何其他技术编写的COM组件没有什么不同。垃圾收集器不会收集从COM引用引用的任何.NET对象。