Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of C++/CLI?

Tags:

.net

c++-cli

I am wondering what the uses of C++/CLI is. It seems to me that it is basically C++ running on .Net, am I wrong in this thinking? What is it good for? Why not just use C# or some other truly managed language instead?

like image 600
Earlz Avatar asked Nov 28 '22 15:11

Earlz


2 Answers

Here are a couple of advantages of C++/CLI over simply C++ or say C#

  • It's a great language for writing a large component which interops between native and managed code.
  • Provides a fast(er) conversion path from a purely native C++ code base to a purely managed one. Without C++/CLI your best option would be a rewrite
like image 145
JaredPar Avatar answered Nov 30 '22 03:11

JaredPar


C++/CLI has a few interesting things that C# does not have:

  • Strongly-typed boxing. If you box an int to an object in C#, you lose any information about what the original type was. Not the case in C++/CLI.

  • A distinction between destructors and finalizers. In C# you have to manually implement IDisposable and remember to call Dispose. In C++/CLI, you just chuck the cleanup code in the destructor (which automatically gets compiled into a Dispose method), and put the managed-only cleanup code in the finalizer.

  • A distinction between stack and heap semantics for variables. Stack is the default, and stack-allocated reference types will automatically be destroyed (disposed) - you don't have to remember to delete them, just let them go out of scope. To make a long story short, it's a lot easier to deal with unmanaged resources in C++/CLI than any other .NET language.

  • Function pointers. This is less of a distinction now with anonymous delegates and lambda syntax in C#, but back in 2005 this was kind of a big deal.

  • Access to all of the access modifiers implemented in the CLR. You can explicitly specify public, protected or private for both the same assembly and external assemblies. All you have in C# (other than the obvious public, protected, private) are the internal and protected internal modifiers, the former meaning "public internally, private externally" and the latter meaning "public internally, protected externally". In C++ you can make a class "protected AND internal", which means that the member is only accessible to derived classes in the same assembly.

  • Value classes. Weird, but probably useful to someone!

There's a more detailed explanation of all this and more here. To make a long story short, other managed languages - C#, VB.NET, F#, and so on - do not actually give you full access to everything that the CLR can do, more like 90% of it. C++/CLI lets you do pretty much anything you want that's in the CLR spec.

like image 26
Aaronaught Avatar answered Nov 30 '22 03:11

Aaronaught