visual c++ - How to wrap class that passes unmanaged class in constructor? -
i trying understand c++/cli can create wrapper classes c++ code. problem have class stores pointer parent object of class, therefore need pass class.
below example, full class has more functions , stores data.
class { private: a* parent; public: a(a* parent) { parent = parent; } ~a() { delete parent; } a* getparent() { return parent; } }
my current idea have non-public constructor can construct managed class unmanaged 1 without being accessible outside class.
public ref class manageda { a* unmanaged; manageda(a* unmanaged) { this->unmanaged = unmanaged; } public: manageda(manageda^ parent) { unmanaged = new a(parent->unmanaged); } ~manageda() { delete unmanaged; unmanaged = null; } manageda^ getparent() { return gcnew manageda(unmanaged->getparent()); } }
while works functions inside class, still have issues if want create object or if have function needs unmanaged class passed in.
is there way can work around this?
manageda^ getparent() { return gcnew manageda(unmanaged->getparent()); }
you shooting leg off code this, very dangerous. problem is, creating multiple manageda objects refer exact same a*. one of them gets destroyed, other manageda objects have dangling pointer. that's guaranteed cause memory corruption.
the solution simple, store parent reference in constructor:
public ref class manageda { private: a* unmanaged; manageda^ parent; public: manageda(manageda^ parent) : parent(parent) { a* unmanagedparent = parent == nullptr ? nullptr : parent->unmanaged; unmanaged = new a(unmanagedparent); } manageda^ getparent() { return parent; } ~manageda() { this->!manageda(); unmanaged = null; } !manageda() { delete unmanaged; } };
note added nullptr check in constructor, sane way see how first a* ever created.
that easy case, exact same object identity problem occurs when ever need map a* manageda^. first check if really needed, client code expected ever manipulate manageda objects. when necessary, you'll need create lookup table can reliably find corresponding manageda^ back. requires static dictionary<intptr, manageda^>
. add objects dictionary in constructor, remove them in finalizer. note forgot include finalizer, not optional. added snippet.
Comments
Post a Comment