I am wrapping some functionality from a native C++ dll to .NET with C++/CLI. One of my native classes (class UA) has a method that returns a reference to another native class/object (class UB). I have wrapped both classes in my C++/CLI project as follows:
//Unmanaged classes
class UA
{
public:
A(int x) : m_x(x) {}
int m_x;
};
class UB
{
public:
UB() : a(1) {}
UA& get_A(){return a;}
protected:
UA a;
};
// managed classes /CLI
public ref class A
{
internal:
A(UA* a) : m_ptr(a) {}
public:
A() : m_ptr(new UA(1)) {}
~A()
{
this->!A();
}
!A()
{
if (m_ptr != nullptr)
{
delete m_ptr;
}
}
private:
UA* m_ptr;
};
public ref class B
{
public:
B() : m_ptr(new UB()) {}
A^ get_A(){return gcnew A(&m_ptr->get_A())}
~B()
{
this->!B();
}
!B()
{
if (m_ptr != nullptr)
{
delete m_ptr;
}
}
private:
UB* m_ptr;
};
The above compiles with /clr
; however, when tested in a C#.NET app, I get a Debug Assertion Error.
// C#.NET app
B b = new B();
A = b.get_A();
This error occurs in the finalizer (!A())
of the managed wrapping class A
. In particular, it is raised when the GC is trying to delete the native pointer. I guess this happens simply why I have not created this instance with the new keyword. Do you think that it would be better to use a copy constructor in the native C++ and then create a managed wrapping class with the new keyword?
For example:
//Unmanaged classes
class UA
{
public:
A(int x) : m_x(x) {}
A(const A& a)
{
m_x = a.m_x;
}
int m_x;
};
And then the managed A and B wrappers will be:
// managed classes /CLI
public ref class A
{
internal:
A(UA* a) : m_ptr(a) {}
public:
A() : m_ptr(new UA(1)) {}
~A()
{
this->!A();
}
!A()
{
if (m_ptr != nullptr)
{
delete m_ptr;
}
}
private:
UA* m_ptr;
};
public ref class B
{
public:
B() : m_ptr(new B()) {}
A^ get_A(){return gcnew A(new UA(&m_ptr->get_A()))}
~B()
{
this->!B();
}
!B()
{
if (m_ptr != nullptr)
{
delete m_ptr;
}
}
private:
UB* m_ptr;
};
Is there any different approach to return a reference to an unmanaged object in C#? Apologies if I do something fundamentally wrong, I have very small experience in C++/CLI. I also have seen this post; however, it seems that the accepted answer proposes the solution I firstly implemented. I appreciate any help/suggestion.
A^ get_A(){return gcnew A(&m_ptr->get_A())}
. Pointer inA
object refers to the object in another object. When you destroyA
it tries to delete an object which was already deleted. – vahancho