Upgrading from C++ to C# - c#

I have a large application written in C++, For various reasons I am going to rewrite it in C#, I have done plenty of Delphi to C#, VB to C# but C++ to C# I have never done, although I am competent in C++ I want this to be as smooth a conversion as possible.
Mainly what I am asking is what pitfalls await me in this conversion is there any key areas I should be aware of or any advice you can provide me.
This article is quite good, but is there anything else I should be weary of?
http://msdn.microsoft.com/en-us/magazine/cc301520.aspx

Main pitfall - do not think it's an upgrade. These are DIFFERENT languages, and in many places you will need complete different approach to the problems. So you should think reimplementation with minimal code reuse.
This article is decent.

I'd advice you to pay attention to the objects lifecycle.
In C++ you destroy objects explicitly when you've done with them. In C# (.NET) you don't. It can happen that an object holds on to some important resource (file handle, database connection etc.). If it is an issue, make use of the using directive.

You need to translate the spirit of the code, but not the code itself. You need to leave behind all the things you had to do in C++ because that was how it was done there. Good translation is highly creative process, so be creative.

The handling of strings was a pitfall for me at the beginning. While I Visual C++ you use pointers the methods in C# have indeed return values.
dummy = dummy.Replace("a", "b");

If you have C++ dll and you want to use them in your C# project you can used them by pinvoke and DllImport
There will be lot of differences while you will try to convert or rewrite unmanaged code to managed one. Here is a C++ to C# converter which is quite good for converting your c++ code to C# , though you can not expect to convert the whole project using it.

Related

How to create a c# wrapper for a software in VC++?

I need to create a VC++ wrapper in C#. Is there a way to automatically generate the code?
Edit: let me clarify a bit: I have a simple project with complicated math functions (computing magnetic declination) in c++. Its just three files, one header, one command line controller and the library.
I was looking at SWiG but I found it to be enigmatic :P. I'm taking a look at C++/CLI.
Any tips and pitfalls to watch for?
Take a look at: Using Unmanaged C++ Libraries (DLLs) in .NET Applications
Or you can use C++/CLI
SWiG supports C#. But a C++/CLI wrapper will be much more ".NET-like" than one automatically generated by SWiG.
You can have a look at this tutorial:
http://www.codeguru.com/csharp/csharp/cs_data/article.php/c4217
I think it's better if you make your own wrapper than using any tool (if it does exists). The reason is that you can create a better C# wrapper using the right philosophies instead of generating a list of function call from a DLL.
And for the pitfalls, the only thing I can say is that since you are going to mix manage and unmanaged class, be sure that your struct/parameters are matching (sizeof or types).
As for most short questions: It depends on your settings and requirements! ;-) If you have a more C style interface, you might be able to solve your problem just by using Interop. If "real" OO progamming and C++ are involved, you probably have to look at C++/CLI. That can be easy, but it can also become painful - depending on your classes. As far as I know, there's not automatic code generation tool.

what are the possible ways to using c# code in c++

I'm just looking for a best way to re-use code written in c#, in my c++ projects. Creating a com\service doesn't look like a best option for my needs. How difficult it is to export c# code into a dll and use it in c++? can i get some suggestion or example? is this usual requirement or ? Please help me.
i use win7, VS2008, win7sdk
Thanks & Rgds, ~calvin
Executing managed code from an unnamaged executable is possible, though not quite easy. You can look into this article for an introduction and this book to go further.
I personally would avoid this kind of things in most cases and, if possible, switch the C++ project to C++/CLI to obtain an immediate compatibility with .Net assemblies for a minimal cost.
You can't export C# code into a native dll afaik. At least without very much pain in your buttocks. You should have thought beforehand and write the reusable part in C, thus creating a native DLL which could be used from all languages.
Also, you could try managed C++ - I personally hate it... but there you go
In case you need to use code written in C# C++, then you need to first see what all data types you would be passing from your C++ code to C# code.
1. Basic data types like int, enum etc can be passed from unmanaged to managed code.
2. in case you want to pass on class object, than you need to use marshalling.
If you can't use COM (if the .NET code is already written for example), then you can host the CLR, but this is a long road...
See these other articles
How to load CLR into process and Create a C# DLL That Can Be Imported in a Delphi App Using stdcall - Possible?

Should a WPF application be written in C++/CLI or C#?

WPF applications are, at its core, managed applications? Right? So, I have to choose between using managed C++ or managed C#. I experimented with managed C++ years ago. It seemed to be not quite be ready for primetime. I'm guessing Microsoft has put more effort into managed C# than managed C++. So, it seems like using managed C# is the best alternative between the two. Is this the case? What experiences have you had with WPF in either language? Thanks in advance.
Managed C++ has been replaced by C++/CLI, and "managed C#" is just C#.
I would strongly recommend you to use C# for a new project, and use C++/CLI only when needed. C# has a better support, has a larger user base, and is easier to work with inside Visual Studio 2010.
Additionally, keep in mind that C++ and C++/CLI are two different languages. For my first .Net project, I chose C++/CLI because I already knew C++, and this was a very bad idea: the learning curve from C++ to C++/CLI is similar to learning C# from C++: don't fall into that trap.
C++/CLI was only really made to support writing interop layers between unmanaged code (i.e. native C/C++) and managed code. For "heavy lifting", you should definitely use C# (or VisualBasic.NET).
You can use managed C++ for your backend but, on inspection, VS (I'm using 2010 Ultimate) doesn't have any in-built templates for a C++ WPF application - only C# or VB.
I'm sure you could force it to work if you wanted to, but I'd suggest you use C#.
C# is the most used, so if you have trouble, there is more online support for C#. C# also has better support by Microsoft. It's overall just a more finished product, even now. If you really don't care yourself, i'd go with C#.
In terms of the backend, they both run on the CLR and both capable of the job. Really it just comes down to what you're most comfortable with. If you're not sure, experiment with both.
Use whatever feels most productive.
Edit:
As has just been pointed out to me though, it seems support for WPF templates (and possibly even intellisense) just isn't there for C++. So in that case I guess I'd have to recommend C#.
IMO without a doubt C# (or VB/F#).
C++/CLI is great when crossing the border of managed world and a c++ library. Complexity is higher though as subtle issues arises from the fact that one combine a managed language and an unmanaged.
Compile times are longer though as well in C++/CLI especially since the code templates are modelled after how the C# compiler works not on how the C++ compiler works.

What are the advantages of doing 100% managed development using C++/CLI?

What are the advantages (the list of possible disadvantages is lenghtly) of doing 100% managed development using C++/CLI (that is, compile with /clr:safe which "generates ... assemblies, like those written in ... C#")? Especially when compard to C# (note C++/CLI : Advantages over C# and Is there any advantage to using C++/CLI over either standard C++ or C#? are mostly about managed/unmanaged interop).
For example, here are a few off the top of my head:
C++-style references for managed types, not as elegant as full blown non-nullable references but better than nothing or using a work-around.
templates which are more powerful than generics
preprocessor (this may be a disadvantage!, but macros can be useful for code generation)
stack semantics for reference types--automatically calling IDisposable::Dispose()
easier implementation of Dispose() via C++ destructor
C# 3.0 added auto-implemented properties, so that is no longer a C++/CLI advantage.
I would think that the single biggest advantage is the managed/unmanaged interop. Writing pure managed C++/CLI would (to me at least) without interoping with C# or other .Net languages seems like missing the point entirely. Yeah you could do this, but why would you.
If you're going to write pure managed code why not use C#. Especially (like nobugs said) if VS2010 drops IntelliSense support for C++/CLI. Also in VS2008 the IntelliSense for C++/CLI isn't as good the C# IntelliSense; so from a developer standpoint, it's easier to work/explore/refactor in C# than C++/CLI.
If you want some of the C++ benefits you list like the preprocessor, stack semantics and templates, then why not use C++?
Odd, I like C++/CLI but you listed exactly its features I dislike. My criticisms:
Okay. But accidental use of the hat is pretty widespread, getting the value of the value type boxed without warning. There is no way to diagnose this mistake.
Power that comes at a high price, templates you write are not usable in any other .NET language. If anything, it worsens the C++ template export problem. The complete failure of STL/CLR is worth pondering too.
Erm, no.
This was IMO a serious mistake. It already is difficult to avoid problems with accidental boxing, as outlined in the first bullet. Stack semantics makes it seriously difficult for any starting programmer to sort this out. This was a design decision to placate C++ programmers, that's okay, but the using statement was a better solution.
Not sure how it is easier. The GC.SuppressFinalize() call is automatic, that's all. It is very rare for anybody to write a finalizer, but you can't avoid the auto-generated code from making the call. That's inefficient and a violation of the 'you don't pay for what you don't use' principle. Add to this that writing the destructor also forces a default finalizer to be auto-generated. One you'd never use and wouldn't want to be used if you forgot or omitted to use the destructor.
Well, that's all very subjective perhaps. The death-knell will come with VS2010, it will ship without IntelliSense support for C++/CLI.
In C++/CLI you can define functions outside of classes, you can't do that in C#. But I don't know if that is an advantage
Like others here, I can't think of any general cases where a clear advantage exists, so my thinking turned to situational advantages -- are there any cases where there is an advantage in a particular scenario?
Advantage: Leverage the C++ skill set of technical staff in a rapid prototyping scenario.
Let me elaborate ...
I have worked quite a bit with scientists and (non-software) engineers who aren't formally trained programmers. Many of these people use C++ for developing specific modules involving high-end physics/mathematics. If a pure .NET module is required in a rapid prototyping scenario and the skill set of the scientist/engineer responsible for the module is C++, I would teach them a small amount of additional syntax (public ref, ^ and % and gcnew) and get them to program up their module as a 100% managed C++/CLI DLL.
I recognize there are a whole heap of possible "Yes, but ..." responses, but I think leveraging the C++ skill set of technical staff is a possible advantage of C++/CLI.
I agree on what you have mentioned and as an example of preprocessor use point to: Boost Preprocessor library for generating a set of types based on a list of basic types e.g. PointI32, PointF32 etc. in C++/CLI
You can have enums and delegates as generic constraints in C++/CLI, but not in C#.
https://connect.microsoft.com/VisualStudio/feedback/details/386194/allow-enum-as-generic-constraint-in-c
There is a library to simulate these constraints in C#.
http://code.google.com/p/unconstrained-melody/
One could imagine the following requirements for a hypothetical product:
Quick time-to-market on Windows
Eventual deploy to non-Windows platforms
Must not rely on Mono for non-Windows
In such a scenario, using eg C# for 1 would stymie you on 2 and 3 without a rewrite. So, one could develop in C++/CLI, suitably munged with macros and template shenanigans to look as much like ordinary C++ as possible, to hit reqt 1, then to hit reqt 2 one would need to (a) reimplement said macros and template shenanigans to map to pukka C++ and (b) implement .NET framework classes used in pukka C++. Note that (a) and (b) could be reused in future once done once.
The most obvious objection would be "well why not do the whole thing in native C++ then?"; well maybe there's lots of good stuff in the vast .NET class library that you want to use to get to market asap.
All a bit tenuous I admit, so I very much doubt this has ever been done, but it'd be a fun thing to try out !

C# --> Java code generator

I have a small (~2000 lines of code) class that I would like to use from both java & .NET. There are several approaches to do this - among them wrapping the class as a service, using some interop voodoo, or duplicating the code to both C# & java.
Do you know an out-of-the-box tool that accomplishes the latter - takes a simple C# class with no dependencies and converts it to an equivalent java class?
IKVM.NET does pretty good job in taking a jar file and compiling it to a managed .NET assembly.
If it is small (or in fact, even if it is large), I'm not sure of the wisdom of mechanical translation tools; I've simply never had much joy with them. However, one option would be to write the .NET code in J#.
But I stress - if it was me, I'd manually port it between the two manually and maintain them separately. Most of the time the differences aren't huge - signed bytes, the boxing differences, etc. Of course, anything with delegates will need changing - and captured variables work differently, etc etc.
There used to be a COM bridge and you can register C# assemblies for use in COM with regasm.exe or visual studio.
It's not really what you asked for, but I would just create a simple C# to Java translator.
The differences are not that huge and you seem to be the author of the source so you can avoid nasty constructs that are quite difficult to translate. That way your translator would be quite simple. I would go from C# to Java because C# is more expressive, and you can emulate almost all the C# functions in Java.
Actually cs2java seems to do just that.
This is list of tools I know. Sharpen or j2cstranslator looks like good options.

Categories