.net - VC++/CLI: How to prevent an unmanaged object from being destroyed when it goes out of scope? -


i have third-party unmanaged c++ library has 2 classes, let's call them classa , classb. classa has method, let's call gettheb(), returns instance of classb - not return pointer instance, instance itself.

i wrote managed wrapper classa in turn has method gettheb() returns managed wrapper wrapping classb.

the original classb object third-party library has handed on managed wrapper via pointer, like:

thirdparty::classb db = delegateforclassa -> gettheb(); managedclassb^ mb = gcnew managedclassb(&db); 

however, when wrapped gettheb() of classa wrapper finishes , scope ends, managedclassb instance contains dangling reference third-party classb , destructor of latter 1 called, leading funny results when accessing methods of classb.

in other question, told somehow store original classb object, don't know how.

so, how keep third-party classb instance alive?

you can either change gettheb return heap-allocated classb, or have managedclassb make own copy of db object.

update copy:

i assume managedclassb's constructor looks like

public ref class managedclassb { public:     managedclassb(classb* p)         : m_p(p) { } ... private:     classb* m_p; }; 

you should change to

public ref class managedclassb { public:     managedclassb(const classb& b)         : m_b(b) { } ... private:     classb m_b; }; 

or

public ref class managedclassb { public:     managedclassb(classb* p)         : m_p(new classb(*p)) { } ... private:     classb* m_p; }; 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -