MC++ FAQ
Saturday 03 | 06 | 2004
Packing for __nogc Classes
On compilation units compiled with the /clr flag as managed code, the compiler will still respect #pragma pack directives for __nogc classes and structs. One interesting question is how the compiler deals with this at the IL level.

As it turns out, the compiler will generate for some __nogc classes managed metadata, depending on how it is used and whether it is used on a public signature. However, this metadata is very opaque, consisting just of empty value type descriptions.

Let's consider an example:


#using <mscorlib.dll>

#pragma pack(1)
__nogc class A { public: int a; char b; int c; }; 
#pragma pack()


A* GetA() { return new A(); }
int main()
{
A a;
}

Compiling this code will generate the following metadata for A (as seen by ILDASM):


.class private sequential ansi sealed A
       extends [mscorlib]System.ValueType {
  .pack 1
  .size 9
} // end of class A

What's interesting about this declaration is the use of the .pack and .size directives. For __nogc types, the MC++ compiler will always generate a .pack 1, regardless of the actual packing used by the type. This can easily be proved by changing the #pragma pack in the code above and recompiling.

The second interesting thing to note is the use of the .size directive. Since the .NET Runtime has no way to calculate the size of an instance of A (given that it's an opaque declarations with no members), the compiler needs to add metadata that tells the runtime what an instance of A would look like the compiler lays it out in memory. And here is the key to understading how packing for __nogc types works: The MC++ compiler will adjust the value used in the .size directive according to the packing! For A, with packing==1, then size would be equal to 9 (sizeof(int)*2+sizeof(char)).

If you changed the code above to use packing==4, you'd get the following signature:


.class private sequential ansi sealed A
       extends [mscorlib]System.ValueType {
  .pack 1
  .size 12
} // end of class A


Notice how the size jumped to 12.

Posted by tomasr at March 06, 2004 02:57 PM
Copyright(C) 2002, Tomas Restrepo, All rights reserved. Powered by Movable Type 2.63