<p>I have a small to medium project that is in C++/CLI. I really hate the syntax extensions of C++/CLI and I would prefer to work in C#. Is there a tool that does a decent job of translating one to the other?</p>

<p><strong>EDIT:</strong> When I said Managed c++ before I apparently meant c++/CLI</p>

[{'answer_id': 73894, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 2, 'selected': False, 'text': '<p>.NET Managed C++ is like a train wreck. But have you looked into C++ CLI? I think Microsoft did a great job in this field to make C++ a first class .NET citizen.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/magazine/cc163852.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc163852.aspx</a></p>\n'}, {'answer_id': 74078, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 1, 'selected': False, 'text': "<p>Back ~2004 Microsoft did have a tool that would convert managed C++ to C++/CLI ... sort of.  We ran it on a couple of projects, but to be honest the amount of work left cleaning up the project was no less than the amount of work it would have been to do the conversion by hand in the first place.  I don't think the tool ever made it out into a public release though (maybe for this reason).</p>\n\n<p>I don't know which version of Visual Studio you are using, but we have managed C++ code that will not compile with Visual Studio 2005/2008 using the /clr:oldSyntax switch and we still have a relic VS 2003 around for it.  </p>\n\n<p>I don't know of any way of going from C++ to C# in a useful way ... you could try round tripping it through reflector :)</p>\n"}, {'answer_id': 74286, 'author': 'Vivek', 'author_id': 7418, 'author_profile': 'https://Stackoverflow.com/users/7418', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not sure if this will work, but try using <a href="http://www.red-gate.com/products/reflector/" rel="nofollow noreferrer">.Net Reflector</a> along with <a href="http://www.codeplex.com/reflectoraddins/Wiki/View.aspx?title=ReflectionEmitLanguage&amp;referringTitle=Home" rel="nofollow noreferrer">ReflectionEmitLanguage</a> plug-in. The RelelectionEmitLanguage plug-in claims to convert your assembly to c# code.</p>\n'}, {'answer_id': 74356, 'author': 'Kevin', 'author_id': 6386, 'author_profile': 'https://Stackoverflow.com/users/6386', 'pm_score': 4, 'selected': True, 'text': "<p>You can only translate Managed C++ code (and C++/CLI code) to C# if the C++ code is pure managed.  If it is not -- i.e. if there is native code included in the sources -- tools like .NET Reflector won't be able to translate the code for you.</p>\n\n<p>If you do have native C++ code mixed in, then I'd recommend trying to move the native code into a separate DLL, replace your calls to DLL functions by easily identifiable stub functions, compile your project as a pure .NET library, then use .NET reflector to de-compile into C# code.  Then you can replace the calls to the stub functions by p-invoke calls to your native DLL.</p>\n\n<p>Good luck!  I feel for you!</p>\n"}, {'answer_id': 74915, 'author': 'Assaf Lavie', 'author_id': 11208, 'author_profile': 'https://Stackoverflow.com/users/11208', 'pm_score': 0, 'selected': False, 'text': "<p>Such projects are often done in c++/cli because C# isn't really an elegant option for the task. e.g. if you have to interface with some native C++ libraries, or do very high performance stuff in low level C. So just make sure whoever chose c++/cli didn't have a good reason to do it before doing the switch.</p>\n\n<p>Having said that, I'm highly skeptical there's something that does what you ask, for the simple reason that not all C++/cli code is translatable to C# (and probably vice versa too).</p>\n"}, {'answer_id': 71609586, 'author': 'Shahin Dohan', 'author_id': 1469494, 'author_profile': 'https://Stackoverflow.com/users/1469494', 'pm_score': 1, 'selected': False, 'text': '<p>It has to be done manually unfortunately, but if the code is mostly C++/CLI (not native C++) then it can actually be done pretty quickly. I managed to port around 250,000 lines of C++/CLI code into C# in less than a couple of months, and I don\'t even know C++ very well at all.</p>\n<p>If preserving Git history is important, you might want to <code>git mv</code> your cpp file into a cs file, commit, then start porting. The reason for this is that Git will think your file is new if you modify it too much after renaming it.</p>\n<p>This was my approach when porting large amounts of code (so that it wouldn\'t take forever):</p>\n<ul>\n<li>Create another worktree / clone of the branch and keep it open at all times\n<ul>\n<li>This is extremely important as <strong>you will</strong> want to compare your C# to the old C++/CLI code</li>\n</ul>\n</li>\n<li>Rename cpp to cs, delete header file, commit\n<ul>\n<li>I chose to rename the cpp file since its git history is probably more important than the header file</li>\n</ul>\n</li>\n<li>Create namespace + class in cs file, add any base classes/interfaces (if abstract sealed, make static in C#)</li>\n<li>Copy fields first, then constructors, then properties, and finally functions</li>\n<li>Start replacing with <code>Ctrl+H</code>:\n<ul>\n<li><code>^</code> to empty</li>\n<li><code>::</code> to <code>.</code></li>\n<li><code>-&gt;</code> to <code>.</code></li>\n<li><code>nullptr</code> to <code>null</code></li>\n<li><code>for each</code> to <code>foreach</code></li>\n<li><code>gcnew</code> to <code>new</code></li>\n<li><code>L&quot;</code> to <code>&quot;</code>\n<ul>\n<li>Turn on case sensitivity to avoid accidental renames (for example <code>L&quot;cool&quot;</code> should become <code>&quot;cool&quot;</code>, not <code>&quot;coo&quot;</code></li>\n</ul>\n</li>\n<li>Prefixes like <code>ClassName::</code> to empty, so that <code>MyClass::MyMethod</code> becomes <code>MyMethod</code></li>\n<li>Go through the red code and port manually code that cannot be just replaced (e.g. some special C++ casts), unless you have some cool regex to do it fast</li>\n<li>Once code compiles, go through it again, compare to C++/CLI line by line, check for errors, clean it up, move on.</li>\n<li>If you encounter a dependency that needs to be ported, you could pause, port that, then come back. I did that, but it might not be so easy.</li>\n</ul>\n</li>\n</ul>\n<p>Properties were the most annoying to port, because I had to remove everything before and after the getters and setters. I could have maybe written a regex for it but didn\'t bother doing so.</p>\n<p>Once the porting is done, it\'s <strong>very important</strong> that you go through the changes line by line, read the code, and compare with C++/CLI code and fix possible errors.</p>\n<p>One problem with this approach is that you can introduce bugs in variable declarations, because in C++/CLI you can declare variables in 2 ways:</p>\n<ul>\n<li><code>MyType^ variable;</code> &lt;- null</li>\n<li><code>MyType variable;</code> &lt;- calls default constructor</li>\n</ul>\n<p>In the latter case, you want to actually do <code>MyType variable = new MyType();</code> but since you already removed all the <code>^</code> you have to just manually check and test which one is correct. You could of course just replace all <code>^</code>\'s manually, but for me it would have taken too long (plus laziness) so I just did it this way.</p>\n<p>Other recommendations:</p>\n<ul>\n<li>Have a dummy C++/CLI project and a tool like <a href="https://www.linqpad.net/" rel="nofollow noreferrer">LinqPad</a> or another C# project to test differences between C++/CLI and C# if you\'re unsure of a piece of ported code</li>\n<li>Install <a href="https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.MatchMargin" rel="nofollow noreferrer">Match Margin</a> to help highlight similar code (helped me when porting WinForms code)</li>\n<li>ReSharper! It helped with finding bugs and cleaning up the code a LOT. Truly worth the money.</li>\n</ul>\n<p>Some gotchas that I encountered while porting:</p>\n<ul>\n<li><p>Base classes can be called in C++/CLI like so: <code>BaseClass-&gt;DoStuff</code>, but in C# you would have to do <code>base.DoStuff</code> instead.</p>\n</li>\n<li><p>C++/CLI allows such statements: <code>if (foo)</code>, but in C# this has to be explicit. In the case of integers, it would be  <code>if (foo != 0)</code> or for objects <code>if (foo != null)</code>.</p>\n</li>\n<li><p>Events in base classes can be invoked in C++/CLI, but in C# it\'s not possible. The solution is to create a method, like <code>OnSomeEvent</code>, in the base class, and inside that to invoke the event.</p>\n</li>\n<li><p>C++/CLI automatically generates null checks for event invocations, so in C# make sure to add an explicit null check: <code>MyEvent?.Invoke(this, EventArgs.Empty);</code>. Notice the question mark.</p>\n</li>\n<li><p><code>dynamic_cast</code> is equivalent to <code>as</code> cast in C#, the rest can be direct casts (<code>(int) something</code>).</p>\n</li>\n<li><p><code>gcnew</code> can be done without parentheses. In C# you must have them with <code>new</code>.</p>\n</li>\n<li><p>Pay attention to <code>virtual override</code> keywords in the header files, you can easily forget to mark the C# methods with <code>override</code> keyword.</p>\n</li>\n<li><p>Intefaces can have implementations! In this case, you might have to rethink the architecture a bit. One option is to pull the implementation into an abstract class and derive from it</p>\n</li>\n<li><p>Careful when replacing casts with <code>Convert</code> calls in C#</p>\n<ul>\n<li><code>Convert.ToInt32</code> rounds to the narest int, but casting always rounds down, so in this case we should not use the converter.</li>\n<li>Always try casting first, and if that doesn\'t work, use the <code>Convert</code> class.</li>\n</ul>\n</li>\n<li><p>Variables in C++/CLI can be re-declared in a local scope, but in C# you get naming conflicts. Code like this easily lead to hard to find bugs if not ported carefully.</p>\n<ul>\n<li>Example: An event handler can take a parameter <code>e</code>, but also has a try-catch like <code>catch (Exception e)</code> which means there are 2 <code>e</code> variables.</li>\n<li>Another example:</li>\n</ul>\n<pre class="lang-cpp prettyprint-override"><code>// number is 2\nint number = 2;\n\nfor (int number = 0; number &lt; 5; number++)\n{\n   // number is now 0, and goes up to 4\n}\n\n// number is again 2!\n</code></pre>\n<p>The above code is illegal in C#, because there is a naming conflict. Find out exactly how the code works in C++ and port it with the exact same logic, and obviously use different variable names.</p>\n</li>\n<li><p>In C++/CLI, it\'s possible to just write <code>throw;</code> which would create a generic C++ exception <code>SEHException</code>. Just replace it with a proper exception.</p>\n</li>\n<li><p>Be careful when porting code that uses the reference <code>%</code> sign, that usually means that you will have to use <code>ref</code> or <code>out</code> keywords in C#.</p>\n<ul>\n<li>Similarly, pay attention to pointers <code>*</code> and <code>&amp;</code> references. You might have to write additional code to write changes back whereas in C++ you can just modify the data pointed to by the pointer.</li>\n</ul>\n</li>\n<li><p>It\'s possible to <strong>call methods on null object instances</strong> in C++/CLI. Yes seriously. So inside the function you could do <code>If (this == null) { return; }</code>.</p>\n<ul>\n<li>Port this type of code carefully. You might have to create an extension method that wraps over this type of method in order to avoid breaking the code.</li>\n</ul>\n</li>\n<li><p>Check and make sure everything in the old project file <code>vcxproj</code> was ported correctly. Did you miss any embedded resources?</p>\n</li>\n<li><p>Careful when porting directives like <code>#ifdef</code>, the &quot;if not&quot; (<code>#ifndef</code>) looks awfully similar but can have disastrous consequences.</p>\n</li>\n<li><p>C++/CLI classes automatically implement <code>IDisposable</code> when adding a destructor, so in C# you\'ll need to either implement that interface or override the Dispose method if it\'s available in the base class.</p>\n</li>\n</ul>\n<p>Other tips:</p>\n<ul>\n<li>If you need to call Win32 functions, just use P/Invoke instead of creating a C++/CLI wrapper</li>\n<li>For complex native C++ code, better create a C++/CLI project with managed wrappers</li>\n<li>Again, pay attention to pointers. I had forgotten to do <code>Marshal.StructureToPtr</code> in my P/Invoke code which wasn\'t necessary in the C++ version since we had the actual pointer and not a copy of its data.</li>\n</ul>\n<p>I have surely missed some things, but hopefully these tips will be of some help to people who are demoralized by the amount of code that needs to be ported, especially in a short period of time :)</p>\n<p>After porting is done, use VS/ReSharper to refactor and clean up the code. Not only is it nice for readability, which is my top priority when writing code, but it also forces you to interact with the code and possibly find bugs that you otherwise would have missed.</p>\n<p>Oh and one final FYI that could save you headaches: If you create a C++/CLI wrapper that exposes the native C++ pointer, and need to use that pointer in an external C++/CLI assembly, you MUST make the native type public by using <code>#pragma make_public</code> or else you\'ll get linker errors:</p>\n<pre class="lang-cpp prettyprint-override"><code>// put this at the top of the wrapper class, after includes\n#pragma make_public(SomeNamespace::NativeCppClass)\n</code></pre>\n<p>If you find a bug in the C++/CLI code, keep it. You want to port the code, not fix the code, so keep things in scope!</p>\n<p>For those wondering, we got maybe around 10 regressions after the port. Half were mistakes because I was already on autopilot mode and didn\'t pay attention to what I was doing.</p>\n<p>Happy porting!</p>\n'}]
['https://Stackoverflow.com/questions/73879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8508/']