MC++ FAQ
Sunday 06 | 30 | 2002
__nogc Classes with Managed Members
Here's how an unmanaged (__nogc) class can hold references to Managed (__gc) classes as members.

Unmanaged classes cannot directly have members whose type is a managed reference object. In other words, they cannot have instances of __gc classes as members.

However, a __nogc class can do so indirectly, by using the GCHandle structure found in the System::Runtime::InteropServices namespace. Since using it directly is a little more cumbersome than usually necessary, I won't show you how to use it here (besides, it's pretty straightforward). Instead, I recommend you use the gcroot template tucked away in the vcclr.h included with VC++.NET.

The gcroot is just a simple wrapper class that makes using GCHandle painless, by acting as a smart pointer. Here's an example:

__nogc class AppDomainWrapper
{
private:
   gcroot<AppDomain*> m_domain;
public:
   AppDomainWrapper() {
      m_domain = AppDomain::CurrentDomain;
   }
   ~AppDomainWrapper() {
   }
   // more functions here...
   void PrintBaseDir() {
      Console::WriteLine ( S"AppDomain Base Directory: {0}",
                           m_domain->BaseDirectory );
   }
};

Notice that even with the use of gcroot, the unmanaged class should still be compiled with the /clr switch, and only methods of the class compiled inside a managed section (the default with /clr, or specified through a #pragma managed directive) will be able to access the wrapped object.

Finally, notice that a __nogc class can directly hold instances of managed value as members, provided they are declared with sequential or explicit layout (via the StructLayout attribute. Both the C# and MC++ compilers will use sequential layout by default, however, V1 of the MC++ compiler has a bug which causes it to ignore this default on __value classes defined inside the same module as you're using, and thus generate a compile-time error. The workaround for this is to add a StructLayout attribute explicitly to their declarations.

Posted by tomasr at June 30, 2002 11:55 PM
Comments
Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?

Copyright(C) 2002, Tomas Restrepo, All rights reserved. Powered by Movable Type 2.63