Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...