Can we access managed code with an external pointer object?
The question says you are using Managed C ++, and the tags say you are using C ++ / CLI (available in VS 2005 or later). You will probably have a less complicated time with C ++ / CLI.
If this is what you are using, then there are two ways to "translate" from C #. Let's say you have C #:
// Construct
MyClass c = new MyClass();
// Call some method
c.MyMethod();
Console.Writeline(c); // will call ToString on MyClass
// Finished with it
c.Dispose();
You can write it in C ++ / CLI like this:
MyClass ^c = gcnew MyClass;
// Call some method
c->MyMethod();
Console.Writeline(c); // will call ToString on MyClass
// Finished with it
c->Dispose();
The variable c
is called a "handle", not a pointer declared with ^ instead of *. Also we should use gcnew
instead of new
. This is the same as a reference variable in C #, and similar (but not identical) to a pointer in C ++, so we use ->
to access the elements.
Or you can write it like this:
// Create with local scope
MyClass c;
// Call some method
c.MyMethod();
Console.Writeline(%c); // will call ToString on MyClass (note the %)
The first thing to note is that we are declaring it in the style of a C ++ local variable. No need to explicitly gcnew
object. Second, we treat the object as if it were a local variable (or a C ++ reference for such a variable). Therefore, we use. instead of ->
. Third, we can "convert" this local object to a handle by specifying it %
, which acts like the .NET equivalent &
we use with regular pointers. This means "accept an address" or "give me a handle" for an object. Finally, we don't need to call the Dispose
object. The compiler does this for us at the end of the scope we declared it in, since a method Dispose
is the mechanism by which destructors are implemented in C ++ / CLI.
a source to share