Export (0) Print
Expand All

16.2 __nogc Pointers in Managed Classes

Visual Studio .NET 2003

There are no restrictions on __nogc pointer types of members in managed classes.

A common use of __nogc pointers in managed classes is "wrapping" unmanaged C++ classes with managed classes. This is often the easiest way to make an unmanaged class interoperate with other common language runtime targeting languages. Given an unmanaged class C, wrap C with managed class M as follows:

  1. Declare a single data member of M whose type is C*.
  2. For each constructor of C, define a corresponding constructor for M that creates an object of C via operator __nogc new, which calls the corresponding constructor of C.
  3. If the managed class holds the only reference to the unmanaged class, define a destructor for M which calls operator delete on the pointer to C.
  4. For each remaining method in the unmanaged class, the wrapper class declares an identical method and delegates to the unmanaged method.

Example

// mcpp_nested_classes6.cpp
// compile with: /clr /LD
#using <mscorlib.dll>

class CppClass {
public:
   CppClass() {}
   ~CppClass() {}
   int method1() { return 0; }
   void method2(int) {}
};

__gc class MCppClass {
public:
   CppClass *p;
   MCppClass() { p = new CppClass(); }
   ~MCppClass() { delete p; }
   int method1() { return p->method1(); }
   void method2(int i) { p->method2(i); }
};

The exact technique for wrapping an unmanaged class varies according to the semantics of the class. Some classes will be considerably harder than others to wrap correctly. However, it is not always necessary to wrap a class completely for it to interoperate well with other CLS-compliant languages.

Show:
© 2014 Microsoft