views:

677

answers:

6

I have to write program in C#, that converts from C++ source code to C# code. Is there any idea where to start? Do i have to use parser tree? Thanks!

+6  A: 

This is a potentially huge topic, and I doubt it's possible to generally convert C++ to C#.

A couple of options:

  • Write your code in managed C++, then use Reflector to decompile into C#. There is a lot of C++ functionality that doesn't exist in C#, so this won't be 100% successful.
  • Write your code in managed C++ and don't translate it to C#.
Tim Robinson
+1  A: 

That is equivalent to writing a C++ compiler, a job that will take many man years. What exactly are you trying to achieve here?

Regarding the C++ to C# translator mentioned elsewhere, I put the following trivial C++ code through Code2Code and got the less than helpful message "Failed on translation":

template <class T> class C {
   public:
      C() {
         t = new T(100);
      }
      ~C() {
         delete t;
      }
      T * t;
};

int main(int argc, char** argv) {
    C <int> x;
}
anon
+2  A: 

Why write one when there are several free and commercial ones available:

C++ to C# Converter

Migration from C++ to C# (free, but non-commercial use)

Mitch Wheat
Any idea how (or if) these handle template meta-programming?
anon
I don't know, sorry.
Mitch Wheat
Hah, the second one fails at the most trivial tests. It chokes on #include <iostream>. And I tried writing a little metaprogram (computing factorials, which it turns into this rather elegant oneliner:using System; ;)The first one works a bit better. It understands #include <iostream> and cout, but still fails at integral template parameters (but adds an explicit comment explaining this in the output file) :)
jalf
The demo of the commercial one fails even at a simple fstream-read-and-print-all-lines code ;-)Not worth the money!
milan1612
+4  A: 

One of the funny things about c++ is that pre-compilation is Turing complete. This makes writing c++ compilers and tranlators especially fun (I wouldn't think it's fun if I had to do this).

David Lehavi
Hahahahahaha! LOL!
alvatar
A: 

You need to use a "parse tree". I suggest ANTLR. It can generate tree modifying programs in C#.

Unknown
+1  A: 

Generally, you just can't.

I explain: C++ provides many paradigms that just not availible in C# like:

  • RAII
  • Multiple Inheritence
  • Manual Memory Managment
  • Sophisticated template metaprogramming

So, don't expect to convert C++ to useful C# code.

Technically, you can do

  • Partial conversion: ie, conversion of feature that are supported by C# only.
  • Use C# as "high-level-assembly"

Good suggestion: keep writing in C++.

Artyom