Reputation: 373
I have a managed class and would like to set the native class in the create()
method.
ref class ManagedClass {
private:
NativeClass* ptr = nullptr;
public:
void create()
{
NativeClass nativeClass;
nativeClass.set(0);
this->ptr = &nativeClass;
}
};
However, the nativeClass
is deleted when create()
was run. And hence this->ptr
become empty. How to make the local variable nativeClass
does not be deleted?
Upvotes: 0
Views: 81
Reputation: 17638
Local variables cease to exist when the function in which they are defined returns, and any remembered pointer to such a local variable becomes invalid. This is no different in C++/CLI vs. unmanaged C++.
To create an object that persists beyond the create
call, allocate it dynamically and save a pointer to it with ptr = new NativeClass();
(then don't forget to delete ptr;
when no longer needed).
Upvotes: 1