Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect whether #pragma unmanaged is in effect in C++/CLI?

I have a project that includes some performance sensitive native C++ headers making heavy use of templates. For this project we also wrap the headers and add some glue code to expose the functionality to c# and other .NET languages. We'll call this header "layout.h", and we'll assume it's a third party header that I can't change.

In a mixed mode C++/CLI assembly it is relatively easy to make a mistake and #include from a place in the code where #pragma unmanaged (or #pramga managed(push,off) ) . When that happens the templates generate IL, and I get extra managed/unmanaged transitions when running the code and performance goes down the drain.

My question is whether there is a way I can do a compile-time check just before the #include so that compilation fails if I am accidently #including from the wrong context.

// File1.cpp, compiled in a mixed mode C++/CLI assembly with /clr
    ASSERT_UNMANAGED()
    #include <layout.h>

My naive 1st attempt checked #ifdef _MANAGED, but that is always defined whether I'm in a #pragma unmanaged block of code or not.

like image 319
Dave Moore Avatar asked Aug 12 '11 10:08

Dave Moore


1 Answers

The pragma directives must be inserted directly in the include file. In this way, everywhere you include the file an unmanaged section is declared.

Sorry that you have to modify your include file.

like image 158
Luca Avatar answered Oct 21 '22 16:10

Luca