C++/CLI : Advantages over C# - c#

Is there any major advantage of managed C++/CLI over C#. Definitely not the syntax I suppose as the following code in C++/CLI is real ugly,
C++/CLI code:
[Out]List<SomeObject^>^% someVariable
Compare above with C# Code:
out List<SomeObject> someVariable
Just out of curiosity, is there an even uglier syntax in C++/CLI as compared to the above.

It's almost exclusively an interopability language - both for allowing .Net code to access legacy C++ libraries, or for extended existing (native) C++ code bases with access to .Net libraries (and some variations on these themes).
While it is possible to write fully fledged applications solely in C++/CLI, and it even gives you some language features not available in pure C++ (such as garbage collection), I doubt there are many people who would actually do this. If you're already moving away from pure C++ and don't have the goal of interop with .Net there are probably more natural choices (such as D or Scala, for example - depending on which direction you want to go in).
Similarly, moving from pure C# to C++/CLI could arguably bring the advantages of C++ templates, but it's rare that this need would lead to you taking that step.

Easier interoperation with native C++ code is the one advantage.
Whether it's a major advantage is subjective.
Unless you want to mingle with existing native C++ code, you're probably much better off with C#.

I can think of 3 main reasons to use C++/CLI:
You already have a large C++ project and want to use .NET in it (whether you want to migrate it completely in the future or not)
You want to use a library written in C or C++. For simple libraries, you can use C#/PInvoke, but e.g. if the libary comes with a complex type system, you might be better off creating C++/CLI wrappers instead of recreating the type system in C#
Parts in your project are best written in C++. E.g. if you're doing speech recognition or image processing, C++ might simply be better suited for the task.

Being able to use native headers files directly is a huge advantage, but not the only one.
Stack semantics are so much better than anything C# has to offer for IDisposable management. C++/CLI has one uniform syntax for correctly managing variables which are IDisposable and those which aren't, both as local variables and as member fields. Comparison:
ref class MyClass
{
FileStream fs;
}
vs
class MyClass : IDisposable
{
FileStream fs;
void IDisposable.Dispose() { Dispose(true); }
~MyClass() { Dispose(false); }
public virtual void Dispose(bool disposing) { if (disposing) fs.Dispose(); }
}
Now which language is looking ugly?
Then there are templates, interior_ptr, #define, native DLL exports, pointer-to-member, and probably several other things I've forgotten.

Using C++/CLI it is much easy to interact with native C++ code

The advantage of managed C++ is that it is easy to mix managed and unmanaged code. But if all (or almost all) of your code will be managed, then C# should definitely be used (and you can still invoking unmanaged code from C# using the DllImport attribute).

CLI/C++ has many advantages over C#.
STD libraries
Native C++/C cannot be viewed by disassembler (like Reflector) because they are not actually CLI (no need to obfuscate (although a good hacker can already get by this)).
Mingling C/C++ projects as a wrapper to be used with .Net languages. C++/CLI is not a language is just adds support for .Net with C/C++.
Some bit of control on memory via C/C++ pointer pointing to C/C++ objects on the heap.
I hate having to trust in GC to get to an object stuck on the gen 2. Lord knows when that will be released from the managed heap.

Being a predominantly C# programmer, I was finding myself having to use C++/CLI with a bit of pain. However, as an interop language, it FAR outweighs C# for having to work with native code. The C++/CLI IDE in Visual Studio lacks a lot of the features in the C# flavor.
Overall, it has its place and will remain viable as long as native code exists. I wouldn't want to have to create WinForm apps from scratch with the C++/CLI IDE if I didn't have to.

you just turn to c++\cli when you have to, if you can meet you requirement using c#, why bother go c++\cli

Generally, I think the main advantage of C++/CLI is simply familiarity for C++ developers. If you're not coming from a C++ background then go with C#.

unmanaged c++ applications do not need a framework to run, c# will only run on machines with dotnet framework 1, 2, 3 or 4. it surprising how many machines still run without these framework.

Related

Should I use Managed C++ or C# for my application?

If you had to decide between C# and Managed C++, which would you choose and why?
Are there benefits of Managed C++ over C#? Which language do you prefer? What decisions would you make under what circumstances?
I would use managed C++ if I:
Needed to integrate with existing C/C++ code
Needed to port existing C/C++ code to .net
Needed to use .NET objects from C++
Needed to expose .NET object over COM in a more complex way than what .net makes easy
Needed to access hardware directly
Needed to call lots of unmanaged APIs
And already had some skills in C++, as the above tasks will need a experienced C++ programmer. Most of the time I would only consider managed C++ if the company already had a C++ code base, otherwise who is going to maintain the managed C++ code.
In other cases I would always choose C#. Even if I choose managed C++ for part of the system, I would try to write as much of the system as possible in C#.
Think of manage C++ as a bridge building kit for going between the
unmanaged world of C/C++ and the
managed world of .NET.
If you only need to call a few simple APIs from C#, then see pinvoke.net and this overview to find how to call them from C#, as a few lines of complex pinvoke code (prebuilt bridge) in C# is normally better then introducing C++ to a project that is not already using it.
what is the benefit of managed C++
over C#?
C++.net is useful for interacting with C++ and C code (that is, calling external C or C++ libraries, providing callback functions to external modules written in C or C++ and so on.
what language of both would you
prefer?
I would prefer C# for all situations except the one described above (interacting with C and C++).
C# is easier to write, simpler, and geared specifically to use the .NET platform. C++ can do it also, but it has all the complexity of the C++ language plus the extensions needed to use the .NET platform.
Unless you need to interact with native C++ or C code, you're better off using C# in most cases (that is, if you're coding for the .NET platform).
Normally I prefer C++, but when needing to code for .NET, it doesn't beat C#.
Managed C++ is good for interop with C++: for example, if you have a .NET application and your assembly has to interact with a native interface that comes as C++ .lib files (which I had more than once), or with a nice C++ API.
Example: Rithmic (not that you ever heard of them) until recently ONLY supported a C++ API. If you try to access them from C# - good luck ;) Managed C++ allows me to access their API and expose nice .NET objects.
Basically interop. Managed C++ REALLY shines in interop with low level C / C++ API's.
I used managed C++ when I needed to build up new NET component with much ofC++ unmanaged code inside.
I did a specific class used to Marshall some objects forward and back from old C++ code.
I've encountered a problem which was transparent in managed C++, but made a big headache in C# - I had to send a callback function to a C++ unmanaged library, that defined this callback as __cdecl. In C#, the default calling convention is __stdcall, and it is pretty compilcated to move a C# delegate from __stdcall to __cdecl (Actually it requires either a 'shim' unmanaged DLL to do so or using some reflection classes).
In C++, (C++.Net as well), it is just a simple attribute.
I haven't personally written, or read for that matter, too many lines of code in managed C++, but from what I have seen it looks too convoluted and patchy. That said, you might want to use managed C++ if you are really good in C++, and when learning the idioms and patterns of a new language would be too much of a risk.
Use C# if you are quite competent in it. If you are only getting started with C++ and C#, I think, C# is the easier route to take.
I would prefer C#, or specifically .NET, over C++ because of the extensive .NET standard library.

Succinct introduction to C++/CLI for C#/Haskell/F#/JS/C++/... programmer

I'm trying to write integrations with the operating system and with things like active directory and Ocropus.
I know a bunch of programming languages, including those listed in the title. I'm trying to learn exactly how C++/CLI works, but can't find succinct, exact and accurate descriptions online from the searching that I have done. So I ask here.
Could you tell me the pitfalls and features of C++/CLI? Assume I know all of C# and start from there. I'm not an expert in C++, so some of my questions' answers might be "just like C++", but could say that I am at C#. I would like to know things like:
Converting C++ pointers to CLI pointers,
Any differences in passing by value/doubly indirect pointers/CLI pointers from C#/C++ and what is 'recommended'.
How do gcnew, __gc, __nogc work with
Polymorphism
Structs
Inner classes
Interfaces
The "fixed" keyword; does that exist?
Compiling DLLs loaded into the kernel with C++/CLI possible? Loaded as device drivers? Invoked by the kernel? What does this mean anyway (i.e. to load something into the kernel exactly; how do I know if it is?)?
L"my string" versus "my string"? wchar_t? How many types of chars are there?
Are we safe in treating chars as uint32s or what should one treat them as to guarantee language indifference in code?
Finalizers (~ClassName() {}) are discouraged in C# because there are no garantuees they will run deterministically, but since in C++ I have to use "delete" or use copy-c'tors as to stack allocate memory, what are the recommendations between C#/C++ interactions?
What are the pitfalls when using reflection in C++/CLI?
How well does C++/CLI work with the IDisposable pattern and with SafeHandle, SafeHandleZeroOrMinusOneIsInvalid?
I've read briefly about asynchronous exceptions when doing DMA-operations, what are these?
Are there limitations you impose upon yourself when using C++ with CLI integration rather than just doing plain C++?
Attributes in C++ similar to Attributes in C#?
Can I use the full meta-programming patterns available in C++ through templates now and still have it compile like ordinary C++?
Have you tried writing C++/CLI with boost?
What are the optimal ways of interfacing the boost library with C++/CLI; can you give me an example of passing a lambda expression to an iterator/foldr function?
What is the preferred way of exception handling? Can C++/CLI catch managed exceptions now?
How well does dynamic IL generation work with C++/CLI?
Does it run on Mono?
Any other things I ought to know about?
Note: I'm really asking about the peculiarities of C++/CLI, its trapdoors.
Converting C++ pointers to CLI pointers
CLI types don't have to be pointers. In C++/CLI handle (^) is used.
Any differences in passing by
value/doubly indirect pointers/CLI
pointers from C#/C++ and what is
'recommended'.
If you need better interoperability with C#, avoid using pointers. Use all the pointer related stuff in C++/CLI and expose only managed types so that C# applications can use it easily.
The "fixed" keyword; does that exist?
pin_ptr<> is the equivalent.
Finalizers (~ClassName() {}) are
discouraged in C# because there are no
garantuees they will run
deterministically, but since in C++ I
have to use "delete" or use
copy-c'tors as to stack allocate
memory, what are the recommendations
between C#/C++ interactions?
C++/CLI supports deterministic resource management. When you write a destructor, compiler will implement IDisposable interface on the class and convert destructor into Dispose() method. delete will call this Dispose() to do the resource de-allocation. Because of this, you don't have issues in using it from C#. You can wrap the usage in using statement in C# which will ensure call on Dispose.
Attributes in C++ similar to
Attributes in C#?
Yes they are similar.
Can I use the full meta-programming
patterns available in C++ through
templates now and still have it
compile like ordinary C++?
Yes. C++/CLI supports templates on ref classes. You can use metaprogramming techniques like you do in standard C++. But these won't be portable to C#.
Have you tried writing C++/CLI with
boost?
C++/CLI has access to the whole .NET framework. I don't think boost helps much here.
To start with, you're confusing the now-defunct "Managed extensions for C++" which had __gc and __nogc keyword, with the new and currently supported C++/CLI language, which finally provides a proper distinction between pointers (native) and handles (managed objects, they're actually implemented as pointers into garbage collected memory where .NET objects live, but you shouldn't think of them as pointers because they get adjusted automatically by the garbage collector). The two types of pointers are completely distinct, only builtin types are compatible with both and then you just box them to get a handle. You can never have a handle pointing outside the managed heap and you can only get a native pointer into the managed heap for the duration of a pin_ptr lifetime (local scope only). A managed class can hold a pointer to native memory, just like C# can have IntPtr members. Native types can hold handles to managed objects using the gcroot templated type, which wraps System::GCHandle.
The Microsoft C++/CLI compiler is capable of generating either pure MSIL or a mixture of MSIL and native code, depending on whether you use /clr or /clr:pure or /clr:safe (the last restricts /clr:pure to produce only verifiable MSIL). The answers to most of your other questions depend on which of these modes it is in. For example, any MSIL it produces will run on Mono, but mixed native and MSIL won't, because it relies on internals of the Microsoft .NET runtime.
Any limitations apply only to managed types (e.g. ref class, enum class) created with C++/CLI. Native types, even when compiled to pure MSIL, have the full flexibility of the C++ language including multiple inheritance, templates, etc.
C++/CLI catches managed exception types in both native and managed code (/clr forces the /EHa compiler option).
C++/CLI provides a stack semantics syntax (declare a variable whose type doesn't include the ^ suffix meaning handle). This is possible for both local variables and members of managed types. The compiler will automatically produce calls to IDisposable::Dispose for types which implement it in all the usual places (like a C# using block for local variables, automatically create an IDisposable implementation in managed types which calls Dispose on all members).
Lambdas aren't available yet, because in the next version of Visual Studio (2010) they will be added using the syntax defined by the upcoming C++ standard.
You can't run managed code in kernel mode regardless of what compiler you use, C++/CLI changes nothing in this area.
You really have way too many points here for a single question. If you really want me to go through every point I will, but it's going to be a series of blog entries and I'll just leave a link here.

What are the situations or pros and cons to use of C++/CLI over C#

I have been keeping up with .NET CLR for awhile now, and my language of choice is C#.
Up until recently, I was unaware that C++/CLI could produce "mixed mode" executables capable of running native and managed code.
Now knowing this, another developer friend of mine were discussing this attribute and trying to determine when and how this ability would be useful.
I take it as a given that native code has the capability to be more efficient and powerful than managed code, at the expense of additional development time.
In the past, I resorted to strictly native C++ code libraries and used Interop to make use of the functionality I wrote into the native library.
I can see the benefit of not requiring an additional library, but I'm curious as to what all the pros/cons of using C++/CLI over soley managed executable created in C#, or such an executable using Interop to call a purely native C++ library?
(Sidenote: Are the terms Interop/PInvoke interchangeable, as I d.on't understand the difference between the terms, simply seen them used the same way.)
With C++/CLI you can create, broadly speaking, three types of objects:
Managed types. These will compile down to essentially the same IL as the equivalent C#. There is no performance opportunity here.
Native types. Compiles down to native code as if you'd used straight C++.
Mixed mode types. These compile down to managed code, but allow you to refer to native types too.
You might think of (3) as being like writing C# code with PInvoke code to accessing the native stuff - except all the PInvoke stuff is generated for you.
There's more to it than that, of course, as well as some caveats - but that should give you an idea of how it's useful.
In other words it's really a glue language. While you can write fully fledged apps in C++/CLI it's more normal to keep the managed and native parts separate and use C++/CLI to bridge the two more cleanly than with PInvoke.
Another common use is to extend and existing, native, C++ code base with .Net library calls.
Just be careful that you partition your code well as it can be quite subtle sometimes in compiling your pure C++ code down to IL transparently!
As to your sidenote: PInvoke is a particular type of Interop. Interop comes in other forms too, such as COM Interop. In fact, more accurately, PInvoke is a set of language features that make Interop with native code easier.
I've used Managed C++ (the .NET 1.1 precursor to C++/CLI) effectively in the past. I find it works best when you have a native C or C++ library you wish to use in managed code. You could go the whole Interop/PInvoke route, which makes for some ugly C# code and frequently has marshalling issues, or you could write a managed C++ wrapper, which is where C++/CLI really shines.
Because C++/CLI is managed code, you can call it from C# (or VB.NET if you lean that way) in the normal way, by adding a reference to the .DLL. No marshalling, no dllimport, nothing goofy like that. Just normal project references. Additionally, you get the benefit of static linked libraries if your native library is so designed, which is a Good Thing (tm).
Phil Nash really hit the big things. Here's one more that I've hit more than once and is the primary reason I've used C++/CLI in the past:
Some applications are extended by checked all DLLs in some location for exported functions with a particular name. In C#, there's no way to declare a native C-style export, but you can in C++/CLI. I create a "wrapper" in C++/CLI that exports the method, handles any translation of C structs to managed objects and passes the call on to an assembly written in C#.
There are certain types that are not available to other languages, such as templates,
const and tracking handle of boxed value types.
templates are specialized at compile-time. generics are specialized at runtime. Although CLR should cache generics specialization for future use (so you get the same List each time you use it), there is still a performance hit each time a generics specialization is requested.
i know other languages discard the const attribute, but have compile time checking in your C++ code is better than nothing.
Having a type like int^ allows you to access the memory on the managed heap directory without unnecessary unboxing. This can help performance when passing tracking handles of boxed values to functions that expect a tracking handle, such as Console::WriteLine(Object^). Of course the early boxing initialization can not be avoided. In other languages you can store the reference in an Object variable and pass it around to avoid unboxing, but you lose the compile time type check.

Windows API and .net languages

People always advised me that if I am doing some application that should use some Windows APIs to do any process level job, I must use VC++ and not any other .net language.
Is there any truth in that?
Can everything that can be done using VC++ be done in other .net languages also?
Are all the .net languages the same when their capabilities are compared?
If you need to work with native code fairly intimately, C++ is likely to make life easier. However, there's nothing inherently wrong with using P/Invoke to call into the Win32 API from C#, VB.NET, F# etc.
Not all .NET languages are the same in terms of capabilities, although C# and VB.NET are largely equivalent in functionality. I know there are some things which C++/CLI exposes which aren't exposed by C# or VB.NET - I don't know if the reverse is true. (I've no idea what C++/CLI is like for lambda expressions, extension methods etc.)
For most tasks where the class libraries do not provide help, using P/Invoke is usually fine. There are many "rough" APIs out there that benefit from a simple C++/CLI wrapper. It's usually best to do the bare minimum in the C++/CLI code -- effectively massaging what ever ugliness is below for consumption by C#, VB.NET, etc.
When I started programming in .Net, I was using C++/CLI, as I came from a minimal Win32 C++ background. What I found was that I was getting headaches because I didn't understand the fine lines and boundaries between C++/CLI and Win32 C++. Its not as easy as they make it seem to interop between the two. When I learned about P/Invoke, and made my life much easier, and I finally started to progress my skills. P/Invoke is just fine and you don't necessarily need C++/CLI to do that. In my opinion, you either use Win32 C++ completely for low level stuff, or .Net for high level stuff, and I don't really recommend ever trying to interop Win32 C++ with C++/CLI unless you absolutely have to. Even then, its probably just easier to make a Win32 DLL with what you need and P/Invoke the DLL from .Net, or visa versa. Always remember to pick the right tool for the job.

Do you recommend Native C++ to C++\CLI shift? [duplicate]

This question already has answers here:
Is there any advantage to using C++/CLI over either standard C++ or C#?
(4 answers)
Closed 7 years ago.
I have been working as a native C++ programmer for last few years. Now we are starting a new project from the scratch. So what is your thoughts on shifting to C++\CLI at the cost of losing platform independent code. Are there are any special advantages that one can gain by shifting to C++\CLI?
I would recommend the following, based on my experience with C++, C# and .NET:
If you want to go the .NET way, use C#.
If you do not want .NET, use traditional C++.
If you have to bridge traditional C++ with .NET code, use C++/CLI. Works both with .NET calling C++ classes and C++ calling .NET classes.
I see no sense in just going to C++/CLI if you don't need it.
Some questions to consider before switching:
[1] Are you fine with sticking to Windows? There are .NET clones for other OS's, but your app is not going to just run transparently. A complexity you might not need.
[2] Are you considering switching just for the garbage collection support? If so, you can just use some C++ garbage collector libraries. And if you figure out how to leverage std::shared_ptr, you might not feel the need for garbage collectors. An overhead you might not need.
[3] Are you considering C++/CLI because of the garbage collection & all the useful .NET classes that you can leverage? If so, why not just switch to c#. C++/CLI is a transitional technology, and it is best not to invest resources in such things. c# is getting pretty mature and usable.
Personally, I would just stick with C++ ;).
Is there any benefit to you? You will likely lose the ablity to switch to another OS.
don't bother unless you're integrating with .NET apps. Certainly do not use STL/CLR as its performance is truly awful.
Its tempting to flip that switch to use the .NET class libraries, but there are alternatives. If you do this, you will not be able to port your code so easily.
It also seems that the rise of OSS is increasing, so now might be the time to investigate using cross-platform libraries and tools. You can deploy a linux app much more easily than a windows one (by shipping a fully-configured OS!), and you get much better ROI if you deploy linux clients (as they're free).
If I were a businessman, I would be looking to at least have the capability to deploy on linux or mac than just windows-only. Strategically, I would not want to bet that the world stayed with Microsoft in 5 years time.
The main advantage you would get moving to C++/CLI is to get access to the .NET libraries and the framework itself (garbage collection etc.). However, as far as I can tell the main reason C++/CLI exists is to ease the porting of existing C++ code to run in the .NET framework. New projects are encouraged to use C#.
If you need to use existing C++ code mixed in with the .NET framework, then it would make sense to use C++/CLI, but in general you should just begin with C#.
If there is something in .NET that the new project needs to use extensively (maybe simpler GUI design or something), then use C#. if not, then stick with native C++. I don't think you will lose anything by doing that.
I dislike C++/CLI so much that I'd recommend steering clear, as I describe here. Some suggest using C++/CLI as a bridge between standard C++ and C#, but thanks to the way C++/CLI is designed, it is very tedious to use that way (you have to manually create wrappers of normal C++ code that can be called from C#). Therefore, I would recommend SWIG instead for interfacing standard C++ with C# (although admittedly, SWIG has a substantial learning curve).
Take a look at those two articles:
A Critical Overview of C++/CLI, Part I
A Critical Overview of C++/CLI, Part II
I believe that by now you are
convinced as I am that C++/CLI is
neither a "set of extensions to C++"
(in many aspects it’s actually a
subset of C++), nor is it related to
C++ more than any other language with
semicolons and curly braces.
Furthermore, C++/CLI is definitely a
Windows-oriented programming language;
it’s definitely not a language that a
Solaris 10 server or a Nokia mobile
phone will be happy to run. What does
it have anything to do with C++?
One main disadvantage of using C++/CLR is the possibility of losing your IP (intellectual Property) if the code is not obscured suficently. In general I agree with the statements made by other members here. If you want portable code independant of the MS .net vm then native C/C++ is the way to go.

Categories

Resources