tags:

views:

291

answers:

1

From http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute(VS.71).aspx:

[C++] 

[StructLayout(LayoutKind::Explicit, Size=16, CharSet=CharSet::Ansi)]
__value class MySystemTime {
public:
   [FieldOffset(0)] short int wYear;
   [FieldOffset(2)] short int  wMonth;
   [FieldOffset(4)] short int  wDayOfWeek;
   [FieldOffset(6)] short int  wDay;
   [FieldOffset(8)] short int  wHour;
   [FieldOffset(10)] short int  wMinute;
   [FieldOffset(12)] short int  wSecond;
   [FieldOffset(14)] short int  wMilliseconds;
};

Am I imagining this, or are the elements in square brackets not consistent with C++ syntax?

Why go through the trouble of doing all of this when C++ provides adequate tools to specify struct layout within the standard definition of the language (and perhaps with the typically supported #pragma pack() ). Doesn't the compatibility designed into the language guarantee that you can define in C++ any struct you can define in C? I understand the need to be able to explicitly describe the layout of a C struct in other languages, but it seems like it would not be necessary with C++ which provides

extern "C" { }
+1  A: 

The things in square brackets are called attributes, and appear often in C# code. They appear here to have the same meaning, as this is not strictly C++. It has Microsoft extensions to allow integration with the CLI.

When you declare such a struct in C or C++, this does not guarantee a particular memory layout. To control that, you need special pragmas to control "packing". These are platform specific. So what you're seeing here is just the CLR equivalent of that.

Update: that example is from the documentation for an older version of Microsoft's CLI integration for C++, which was called Managed C++. It was abandoned very quickly and replaced in the next version by C++/CLI - a grafting of CLI features into C++ that is so complete and wide-ranging, it effectively becomes a different language just as C++ is a different language from C.

Daniel Earwicker