非托管代码使用的 .NET 组件的内存管理
当在非托管世界中工作时,如果我们在堆上分配了内存(例如,通过使用 C++ 中的 new 关键字),我们必须确保自己进行清理; 我们还必须确保使用 CreateInstance
创建 AddRef
COM 组件,并稍后Release
; 也许是这样的:
SomeNameSapce::IObjPtr obj;
HRESULT hr = obj.CreateInstance(L"SomeObject");
if (hr == S_OK)
{
obj->AddRef();
m_anotherObj= obj->GetObj();
obj->Release();
}
显然我们可以使用智能指针和其他类似的东西(在 C++ 中),但这不是重点...
我们是否还必须为从 COM 组件抓取的对象添加 AddRef/Release
(就像上面例子中的 m_anotherObj 一样)?
更令人困惑的是,如果这个特定组件实际上是一个 .NET 组件,并且通过 COM 接口暴露给非托管代码,会发生什么情况? 垃圾收集器是否知道清理东西,还是在非托管世界中这一切都必须手动完成?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CreateInstance
将返回一个引用计数为 1 的对象,因此您无需AddRef
它。 (您使用的智能指针将在对象被销毁时释放
该对象。)类似地,您从方法接收的对象应该具有已经递增的引用计数,因此您不需要AddRef<再次 /code> 它们 - 但您确实需要
释放
它们,除非您使用智能指针。.NET 公开的 COM 组件与任何其他技术编写的 COM 组件没有什么不同。 垃圾收集器不会收集从 COM 引用引用的任何 .NET 对象。
CreateInstance
will give you back an object with a reference count of 1, so you do not need toAddRef
it. (The smart pointer you have used willRelease
the object when it is destroyed.) Similarly, objects you receive from methods should have the reference count already incremented, so you do not need toAddRef
them again - but you do need toRelease
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.