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

发布于 2024-07-09 16:05:07 字数 620 浏览 5 评论 0原文

当在非托管世界中工作时,如果我们在堆上分配了内存(例如,通过使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自此以后,行同陌路 2024-07-16 16:05:07

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文