C++/CLI 引用类未释放

发布于 2024-11-09 15:52:22 字数 612 浏览 0 评论 0原文

我有一个 unmanged 类和一个 ref 类,它们在逻辑上相连:

public ref class RefBlah
{
   ~RefBlah();
   !RefBlah();

   internal:

   UnManagedBlah* m_unmanaged;
}

public class UnManagedBlah
{
    public:
    gcroot<RefBlah^> refBlah;
}

RefBlah 类始终创建一个 UnManagedBlah 实例,该实例保存对创建它的对象的引用。

现在,当我在 C# 应用程序中创建 RefBlah 实例时,它在超出范围时不会被释放。 (我等待并看到所有其他对象都被释放,但它拒绝删除自身)。

据我所知,如果它们都是常规的 .Net 对象,那么当类超出范围时,它们都会被收集,因为尽管引用计数未达到 0。那是因为主对象中的对象没有引用根堆。

.NET GC 是否以不同方式对待来自非托管类的引用?

我怎样才能改变设计以使 RefBlah 被破坏?

I have an unmanged class and a ref class which ar logically connected:

public ref class RefBlah
{
   ~RefBlah();
   !RefBlah();

   internal:

   UnManagedBlah* m_unmanaged;
}

public class UnManagedBlah
{
    public:
    gcroot<RefBlah^> refBlah;
}

The RefBlah class always creates an instance of UnManagedBlah which holds a reference to the object that created it.

Now, when I create an instance of RefBlah in a C# application, it just doesn't get freed when it get out of scope. (I've waited and seen all the other objects get freed, but it refuses to remove itself).

As far as I know, if they were both regular .Net objects, they would both be collected when the class gets out of scope because although the reference count does not reach 0. And that's because there's no refernce root to the objects from the main stack.

Does .NET GC treat references from unmanaged classes differently ?

How can I change the design so that RefBlah will be destroyed ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

倾城泪 2024-11-16 15:52:22

我认为你有循环引用问题。在 UnManagedBlah 中的引用被 GC 之前,RefBlah 不会被 GC,只有当您删除 RefBlah 等中的指针时才会发生这种情况..

如果您需要在非托管类内部有一个引用,那么也许它应该是一个弱引用?查看 GCHandle 结构:

GCHandle 类与
GCHandleType 枚举创建
对应于任何托管的句柄
目的。该句柄可以是四个句柄之一
类型:Weak、WeakTrackResurrection、
正常或固定。当手柄有
已分配,您可以使用它
防止被管理对象被
由垃圾收集器收集
当非托管客户端持有
仅供参考。如果没有这样的把手,
该对象可以通过以下方式收集
完成之前的垃圾收集器
它代表不受管理的人所做的工作
客户端。

I think you have a circular reference problem. RefBlah won't get GC'd until the reference in UnManagedBlah is GC'd which will only happen when you delete the pointer in RefBlah etc..

If you need to have a reference inside the unmanaged class then perhaps it should be a weak reference? Have a look at the GCHandle struct:

The GCHandle class is used with the
GCHandleType enumeration to create a
handle corresponding to any managed
object. This handle can be one of four
types: Weak, WeakTrackResurrection,
Normal, or Pinned. When the handle has
been allocated, you can use it to
prevent the managed object from being
collected by the garbage collector
when an unmanaged client holds the
only reference. Without such a handle,
the object can be collected by the
garbage collector before completing
its work on behalf of the unmanaged
client.

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