IS4
IS4

Reputation: 13177

What is C++/CLI required for?

Are there any tasks that require you to use C++/CLI and cannot be done in managed code (with P/Invoke and the Marshal class), performance aside?

Upvotes: 2

Views: 203

Answers (2)

Hans Passant
Hans Passant

Reputation: 941237

Sure, C++/CLI is required when you need to interop with libraries that were written in native C++. Neither pinvoke nor Marshal can tackle templates or C++ classes with instance functions. Or any functions that take a standard C++ library object as an argument like std::string, std::vector, etcetera. Or use exceptions to report errors.

And it may be required to use a C library that has a clumsy interface. One that fumbles memory management, requiring the caller to release memory for example. Or uses excessively intricate structs that are too difficult to reproduce in managed code.

COM interop could be an alternative, but that requires pretty substantial changes to the C++ library when it wasn't originally written to support COM clients. Using C++/CLI is much simpler.

Upvotes: 5

user1610015
user1610015

Reputation: 6668

Well first, C++/CLI IS managed code.

While you could use C#/VB.NET with P/Invoke to accomplish most things you could do in C++/CLI, C++/CLI just makes it easier to mix managed code and unmanaged code in one place. For example, it's easier to include Windows.h or any other C++ API compared to having to repeat the declarations in C# and having to figure out how to marshal each parameter and return value.

It's also required in cases where you're using a library or any piece of code that uses C++ classes, as you can't P/Invoke those due to name mangling and other issues. This is one of the most common use of C++/CLI nowadays: to interoperate between native C++ and C#/VB.NET.

Upvotes: 2

Related Questions