Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI What class encloses global functions?

If I remember correctly, functions must be a member of a class in the CLR world, and yet global functions are possible in C++/CLI. Does this mean that these global functions are part of a hidden "global" class of some sort? If so, how would one go about getting its type, for reflection purposes?

like image 902
Mona the Monad Avatar asked Dec 24 '22 19:12

Mona the Monad


1 Answers

Yes, .NET metadata supports global functions and variables. Called the "Global Class" in CLR source code, its name is <Module>. Using C# vernacular, it is internal, abstract and sealed to ensure you can never create an instance of the class, the angle brackets help to avoid create an accidental duplicate type.

Technically you can reflect on it, you'll need BindingFlags.NonPublic and BindingFlags.Static. Do keep in mind how unpractical this is, you need to use the mangled C++ name to find anything back. At least the linker .map file or a disassembler like ildasm.exe is required to know the name. Beware that it is quite messy, lots of CRT identifiers end up in this class for a typical C++/CLI project. Bit of a bug.

And last but not least, it is almost always a mistake to have code in <Module>. Except for obscure reverse-pinvoke reasons, you always want managed code inside a ref class. Especially so if you want to reflect on it. And more worrisome, getting too much native C++ code compiled to MSIL. It works too well, any C++03 compliant code can be compiled to MSIL so you just can't tell that you are basically get the worst of both worlds. Strictly separating C++/CLI from native C++ code is important, most easily done with a static library project.

like image 178
Hans Passant Avatar answered Dec 30 '22 09:12

Hans Passant