Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++-cli

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

like image 868
Xenoprimate Avatar asked Aug 03 '13 20:08

Xenoprimate


People also ask

Which is the correct form to declare main with command line arguments?

B. int main(argc, argv) int argc; char *argv; C.

What is CLI in C?

A command-line interface (CLI) is a text-based user interface (UI) used to run programs, manage computer files and interact with the computer. Command-line interfaces are also called command-line user interfaces, console user interfaces and character user interfaces.


2 Answers

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.

like image 163
Ben Voigt Avatar answered Oct 03 '22 22:10

Ben Voigt


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...".

like image 31
Hans Passant Avatar answered Oct 03 '22 21:10

Hans Passant