How to store a pointer to a ref class (C++/CLI newbie)

I

Ivan Vecerina

We are trying to use a .NET form ("Form") from a non-managed C++
class ("Engine").
The Engine class needs to create the form once (e.g. at construction),
then will be displaying the Form and running a modal loop a few
times. At destruction, the form will be closed and disposed of.

So I wanted to store a kind of pointer or reference to the
garbage-collected Form within the Engine class.

How do we achieve that?
The following naive solution is rejected by the compiler:

using MyNetTest::Form; // a .NET form generated using the Designer

class Engine {
public:
//...

private:
Form^ dlg; //ERROR C3265
};

Error message:
error C3265: cannot declare a managed 'dlg' in an unmanaged 'Engine'
may not declare a global or static variable, or a member of a native
type that refers to objects in the gc heap

There has to be some kind of built-in smart pointer/wrapper
that I can use to make Form a member of Engine, right?
What is the solution?


Thanks,
Ivan
 
T

Tamas Demjen

Ivan said:
class Engine {
public:
//...

private:
Form^ dlg; //ERROR C3265
};

The solution is to use the gcroot template, which is a wrapper around a
low level GC handle:

class Engine {
public:
//...

private:
gcroot<Form^> dlg;
};

Note that gcroot requires manual deletion, it's like an unprotected
pointer that can leak:

Engine::~Engine() { delete dlg; }

Therefore I recommend that you use auto_gcroot, which is a smart pointer
around gcroot, then you don't have to worry about manual deletion:

private:
auto_gcroot<Form^> dlg;

You have to #include <msclr\auto_gcroot.h> in order to use this class.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top