Windows API and .net languages - c#

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.

Related

Wrapping code/classes for another program

At the moment, I am working in a C++ environment. There are many in house programs, SDKs, and DLLs. What I want to know is, moving forward, would I be able to wrap that code into something C# could use? I'm still learning about wrapping code for other languages, and haven't found a decent source for going from C++ to C#.
As far as cross-language interop goes, the C#-C++ interop is actually quite usable. Check out the official documentation. "Managed" is Microsoft-speak for everything in the .NET runtime, i.e. your C# code; "unmanaged" or "native" means your C++ code.
Microsoft has extensions to C++ called C++/CLI that make it easier to build wrappers for .NET languages.

Managed C++ (C++/CLI) vs C#/VB.NET

I have worked extensively with C#, however, I am starting a project where our client wishes all code to be written in C++ rather than C#. This project will be a mix between managed (.NET 4.0) and native C++. Being that I have always preferred C# to C++ for my .NET needs, I am wondering if there are any important differences I may not be aware of between using C# and managed C++?
Any insight into this is greatly appreciated.
EDIT Looking at Wikipedia for managed C++ code shows that the new specification is C++/CLI, and that "managed C++" is deprecated. Updated the title to reflect this.
C++/CLI is a full fledged .NET language, and just like other .NET languages it works very well in a managed context. Just as working with native calls in C# can be a pain interleaving native C++ and Managed C++ can lead to some issues. With that said, if you are working with a lot native C++ code I would prefer to use C++/CLI over C#. There are quite a few gotchas most of which could be covered by do not write C++/CLI as if your were writing C# nor write it as if you were writing native C++. It is its own thing.
I have worked on several C++/CLI projects and the approach I would take really depends on the exposure of different levels of the application to native C++ code. If the majority of core of the application is native and the integration point between the native and managed code is a little fuzzy then I would use C++/CLI throughout. The benefit of the control in the C++/CLI will outweigh its problems. If you do have clear interaction points that could be adapted or abstracted then I would strongly suggest the creation of a C++/CLI bridging layer with C# above and C++ below. The main reason for this is that tools for C# are just more mature and more ubiquitous than the corresponding tools for C++/CLI. With that said, the project I have been working on has been successful and was not the nightmare the other pointed to.
I would also make sure you understand why the client is headed in this direction. If the idea is that they have a bunch of C++ developers and they want to make it simpler for them to move to write managed code I would posit to the client that learning C# may be less challenging then learning C++/CLI.
If the client believes that C++/CLI is faster that is just incorrect as they all compile down to IL. However, if the client has a lot of existing or ongoing native C++ development then the current path may in fact be best.
I've done a project with C++/CLI and I have to say it was an abomination. Basically it was a WinForms application to manage employees, hockey games, trades between teams, calendars etc, etc...
So you can imagine the number of managed controls I had on my forms: calendars / date time pickers, combo boxes, grids etc.
The worst part was to use only C++ types for my back-end, and use the managed types for the front-end. First off you can't assign a std string to a managed string. You'll need to convert everything. Obviously you'll have to convert it back...
Every time I needed to fill a grid, I serialized my C++ collections to something like a vector<std::string>, retrieve that in my UI library and then looped trough that and made new DataGridRow to add them to the grid. Which obviously can be done in 3 minutes with C# and some Linq to SQL.
I ended up with A+ for that application but lets be honest it absolutely sucked. I just can't imagine how pathetic the others app were for me to get that.
I think it would've been easier if i used List<Customer>^ (managed List of some object) in my C++ instead of always converting everything between vectors of strings. But I needed to keep the C++ clean of managed stuff.
/pissedof
From using all three areas (.NET, C++/CLI and C++) I can say that in everyway I prefer using .NET (through C# or VB.NET). For applications you can use either WinForms or WPF (the latter of which I find far better - especially for applications that look far more user friendly).
A major issue with C++/CLI is that you don't have all the nice language features that you get in .NET. For example, the yield keyword in C# and the use of lambda (I don't think that's supported in C++/CLI - don't hold me to that).
There is, however, one big advantage of C++/CLI. That is that you can create a bridge to allow C# and C++ to communicate. I am currently working on a project whereby a lot of math calculations and algorithms have already been written (over many years) in C++, but the company is wanting to move to a .NET-based user interface. After researching into various solutions, I came to the conclusion that C++/CLI was far better for this. One benefit is that it allowed me to build an API that, for a .NET developer, looked and worked just like a .NET type.
For developing an application's front end, however, I would really not recommend C++/CLI. From a usability point of view (in terms of developer time when using it) it just isn't worth it. One big issue is that VS2010 dropped support for IntelliSense for C++/CLI in order to "improve general IntelliSense" (I think specifically for C++). If you haven't already tried it, I would definitely advise checking out WPF for applications.

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.

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.

Mixing C# Code and umanaged C++ code on Windows with Visual Studio

I would like to call my unmanaged C++ libraries from my C# code. What are the potential pitfalls and precautions that need to be taken? Thank you for your time.
There are a couple routes you can go with this - one, you can update your unmanaged C++ libraries to have a managed C++ extensions wrapper around them and have C# utilize those classes directly. This is a bit time-consuming, but it provides a nice bridge to legacy unmanaged code. But be aware that managed C++ extensions are sometimes a bit hard to navigate themselves as the syntax is similar to unmanaged C++, but close enough that a very trained eye will be able to see the differences.
The other route to go is have your umnanaged C++ implement COM classes and have C# utilize it via an autogenerated interop assembly. This way is easier if you know your way around COM well enough.
Hope this helps.
This question is too broad. The only reasonable answer is P/Invoke, but that's kind of like saying that if you want to program for Windows you need to know the Win32 API.
Pretty much entire books have been written about P/Invoke (http://www.amazon.com/NET-COM-Complete-Interoperability-Guide/dp/067232170X), and of course entire websites have been made: http://www.pinvoke.net/.
You're describing P/Invoke. That means your C++ library will need to expose itself via a DLL interface, and the interface will need to be simple enough to describe to P/Invoke via the call attributes. When the managed code calls into the unmanaged world, the parameters have to be marshalled, so it seems there could be a slight performance hit, but you'd have to do some testing to see if the marshalling is significant or not.
The easiest way to start is to make sure that all the C++ functionality is exposed as 'C' style functions. Make sure to declare the function as _stdcall.
extern "C" __declspec(dllexport) int _stdcall Foo(int a)
Make sure you get the marshalling right, especially things like pointers & wchar_t *. If you get it wrong, it can be difficult to debug.
Debug it from either side, but not both. When debugging mixed native & managed, the debugger can get very slow. Debugging 1 side at a time saves lots of time.
Getting more specific would require a more specific question.
You can also call into unmanaged code via P/Invoke. This may be easier if your code doesn't currently use COM. I guess you would probably need to write some specific export points in your code using "C" bindings if you went this route.
Probably the biggest thing you have to watch out for in my experience is that the lack of deterministic garbage collection means that your destructors will not run when you might have thought they would previously. You need to keep this in mind and use IDisposable or some other method to make sure your managed code is cleaned up when you want it to be.
Of course there is always PInvoke out there too if you packaged your code as DLLs with external entrypoints. None of the options are pain free. They depend on either a) your skill at writing COM or Managed C wrappers b) chancing your arm at PInvoke.
I would take a look at swig, we use this to good effect on our project to expose our C++ API to other language platforms.
It's a well maintained project that effectively builds a thin wrapper around your C++ library that can allow languages such as C# to communicate directly with your native code - saving you the trouble of having to implement (and debug) glue code.
If you want a good PInvoke examples you can look at PInvoke.net. It has examples of how to call most of win api functions.
Also you can use tool from this article Clr Inside Out: PInvoke that will translate your .h file to c# wrappers.

Categories

Resources