C++/CLI 引用类未释放
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你有循环引用问题。在
UnManagedBlah
中的引用被 GC 之前,RefBlah
不会被 GC,只有当您删除RefBlah
等中的指针时才会发生这种情况..如果您需要在非托管类内部有一个引用,那么也许它应该是一个弱引用?查看
GCHandle
结构:I think you have a circular reference problem.
RefBlah
won't get GC'd until the reference inUnManagedBlah
is GC'd which will only happen when you delete the pointer inRefBlah
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: