According to this question it's possible to seamlessly combine managed and unmanaged code using C++/CLI. I don't quite get it - shouldn't there be marshalling between managed and unmanaged anyway?
For example, I have InnerLibrary that is compiled as a native C++ .dll with a header published and C++/CLI OuterLibrary that calls code from InnerLibrary. Will there be marshalling? Who will implement it and how costly will it be?
Well, it's a feature that's built into the C++/CLI compiler, called C++ Interop. There's a lot less black magic involved that you might think. The JIT compiler generates the exact same kind of machine code as your C++ compiler generates. All of the .NET value types have a direct equivalent in C++ so no conversion is needed. It does not automatically handle reference types, you have to do that yourself. pin_ptr<>, typically.
All that it really does is inject a bit of code that handles the transition from a managed stack frame to an unmanaged stack frame. That code puts a special "cookie" on the stack, recognized by the garbage collector. Which prevents it from blundering into the unmanaged frames and mis-identify unmanaged pointers as object references. There's not much to that code, takes about 5 nanoseconds in the Release build, give or take.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With