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 ?
I think you have a circular reference problem.
RefBlahwon’t get GC’d until the reference inUnManagedBlahis GC’d which will only happen when you delete the pointer inRefBlahetc..If you need to have a reference inside the unmanaged class then perhaps it should be a weak reference? Have a look at the
GCHandlestruct: