C++/CLI What class encloses global functions?

风格不统一 提交于 2019-12-10 21:48:59

问题


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?


回答1:


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.




回答2:


It's actually a class called "<Module>" (with the angle brackets) that isn't in any namespace. This class is actually present in normal C# assemblies.



来源:https://stackoverflow.com/questions/42880060/c-cli-what-class-encloses-global-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!