C++ CLI Correct way to use #pragma managed / unmanaged

ⅰ亾dé卋堺 提交于 2020-01-21 02:57:05

问题


I'm writing a C++ / CLI application, but I want most of the code in my C++ DLL to run natively (i.e. not managed).

I have only got a single CLI class in the module, the other files are all native C++.

So, what is the best way of ensuring that those native classes are run... Well, natively?

Should I:

  • A) Add #pragma unmanaged to the top of every native class
  • B) Just add #pragma unmanaged before the includes in my single CLI class
  • C) Something else?

Thanks


回答1:


You don't have to jump through hoops to ensure this. The compiler will only ever emit IL when it compiles your program with the /clr option turned on. It looks like a project option but it is not.

Just select your .cpp files that contain native code. Select more than one of them by holding down the Ctrl key and clicking the file in the Explorer windows. Right-click + Properties, C/C++, General. Change the "Common Language Runtime Support" setting to "No...".




回答2:


The usual way I do this is to put the native code into a static library project with no .NET support (compile without /clr). You can turn off /clr for individual files in a C++/CLI project but then precompiled headers get really confused. Using a separate library project, it's easy to have a native pch for the native code and a managed pch for the managed code.

Then I link my C++/CLI code with that native C++ .lib to create the DLL. All you do is set a project dependency and Visual Studio takes care of the rest.

You can also use #pragma managed(push, off) and #pragma managed(pop) if you absolutely have to combine native and managed code in the same compilation unit. But usually any code that's in header files is there because you're intending to have it inlined... which means it should be in managed mode when included into a managed CU, so it can be inlined into managed functions.


Despite his comments maligning this answer, Hans has begun recommending my approach.



来源:https://stackoverflow.com/questions/18037232/c-cli-correct-way-to-use-pragma-managed-unmanaged

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