Can we access managed code with an external pointer object?

I have created some application in managed C ++. When I try to instantiate it, it shows an error like

cannot convert from obj to * obj. when i instantiate obj it shows no error.

So. is there a way to access such a class without creating a pointer object

0


a source to share


2 answers


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.

+2


a source


You can create it on the stack.

MyObject foo;
foo.bar();   // accessing bar method on object foo 

      



Perhaps the syntax you are looking for is this:

MyObject *foo = new MyObject;
foo->bar;

      

0


a source







All Articles