tags:

views:

31

answers:

1

I have a C++/CLI library that calls many native C++ methods. I have read many threads stating that you should not mix managed and unmanaged code. I couldnt find any that says how to avoid those switches and why it will cause a performance issue. Can someone share best practices.

+2  A: 

The only reason to use C++/CLI is for its support of mixing managed and native code. If everything is managed then use C# or VB, if everything is native then use C or C++. Or whatever language you prefer. Clearly avoiding mixing is nonsensical.

There is a small amount of overhead going from managed to unmanaged. The C++/CLI compiler auto-generates a bit of machine code that pushes a 'cookie' on the stack, designed to prevent the garbage collector from blundering into unmanaged stack frames and mis-interpreting pointers on that frame as managed object references. Costs about 7 nanoseconds, give or take.

Hans Passant
especially note: C++ interop is much cheaper than p/invoke. C++/CLI will use C++ interop when two conditions are met: You are building a mixed-mode assembly (no `/clr:pure`) and you are declaring the functions using normal C++ prototypes (usually from the native header file), not p/invoke `DllImport` attributes.
Ben Voigt