how to convert C# to C++ [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Could someone please help me to convert C# to C++? here is an example:
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace read_website
{
class Program
{
static void Main(string[] args)
{
while (true)
{
DownloadString("http://www.xxx.asp");
Thread.Sleep(100);//update every 100 millisecoand
}
}
public static void DownloadString(string address)
{
WebClient client = new WebClient();
string website = client.DownloadString(address);
get_Current_X1_value(website);
}
static void get_Current_X1_value(string web)
{
int x = web.IndexOf("Current X1 value:");
string part1 = web.Substring(x, 100);
string[] array = part1.Split('>', '<');
for (int i = 0; i < array.Length; i++)
{
if (array[i].Contains("Current X1 value:"))
Console.Write(array[i]);
if (array[i].Contains("W"))
Console.WriteLine(array[i]);
}
}
}
}
Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++

Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++
Have you considered Mono? It is something that's definitely worth checking before starting to learn C++ in order convert and run an existing .NET application on Unix. It's also binary compatible meaning that you don't even need to recompile your existing assembly.

Learn C#, learn C++, and spend a lot of time rewriting.
Or use PInvoke from the C# assembly to call into a C++ dll.
Or write managed C++ and compile with the /clr switch. The resulting assembly can be referenced and used from C# projects.

It is nearly impossible to directly translate C# to C++ so that it will run on Unix machines.
This is mainly due to the fact that the .NET Framework is not available (from C++) on Unix machines. Mono will allow you to run many C#/.NET programs, but does not support C++/CLI (the C++ extensions that allow directly working with the .NET Framework).
Converting the language is possible - though difficult due to differences in approach (e.g., garbage collection in C#), but the framework calls will require porting to different libraries, and it is often not a good candidate for a direct translation.
For example, in your code above, you'd have to decide on a C++ library for web access - and once you had that choice made, it would dictate the code required to call into that library to download the website string.

I'm using C# to C++ converter time to time. It's really great for snippet conversion from c# to c++ or c++/cli.

Consider looking at Vala. Vala is a C#-like language that converts into C and then into an executable. There are very little differences with C#. You will still have to use your brain though.

You may want to consider CoreRT. It's a .NET project whose goal is to eliminate the need for the CLR to be present on the target platform for running an application. Instead, it generates C++ code from a given C# code. That C++ code is compiled and linked on any target platform that supports C++.
A post on a Microsoft blog said: "If I really want to write some C# code and have it 'just work' on a new IoT device, I don’t have any options until the RyuJIT is capable of generating machine code that works with that processor and operating system." By cross-compiling C# to C++, .Net developers can then deliver their applications without needing to wait for .Net to be deployed on a given platform.
https://github.com/dotnet/corert

Edit:
The site listed has been discontinued. I'll leave the old answer here for reference ...
Old answer:
Here is an online converter that will automate the process for you! ...
Varycode online converter
It can do C# to C++ and back again as well as converters for Ruby, Python, Java & VB, apparently!
Edit:
It appears to have had its C++ (and java) functionality removed - it says temporarily, but has done so for a long time now. Hopefully they'll resurrect it soon!
Still works for some other languages (VB, Ruby, Python, Boo).

As already mentioned here, the translation of libraries can be an issue, but one open source project that might help at some cases is:
http://alexalbala.github.io/Alter-Native/
Citation from its main page:
It provides a tool to easy port applications
from high-level languages such as .NET to
native languages like C++. It is a research project
and it is under development with the
collaboration of UPC - BarcelonaTech and AlterAid S.L.

Related

Converting Delphi vcl.net application to c# using Reflector

I have used reflector until its trial period ended
I have decoded many applications successfully. And by my recent post i was able to identify it can also decode delphi.net vcl apps (d2007).
Can i decode delphi.net vcl and translate it to a c# application which can be compiled success fully using visual studio.
The answer to the question Can i decode delphi.net vcl app and translate it to a c# application which can be compiled success fully using visual studio ? is No
This is the Why.
When you create a vcl net application using delphi (8), 2005, 2006 or 2007, the delphi compiler create an .NET application with a lot of dependencies to internal classes which are wrappers and helpers to call the real .net classes, these classes (wrappers) was created to facilitate the creation of .net applications to the existing delphi win32 developers.
Consider this sample.
This a delphi .net app
program DelphiNetConsole;
{$APPTYPE CONSOLE}
uses
SysUtils;
begin
try
Writeln('Hello From Delphi 2007.Net');
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
if you translate manually this code to C#
using System;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Hello From Delphi 2007.Net");
}
catch (System.Exception E)
{
Console.WriteLine(E.Message);
}
}
}
}
But using reflector you get this for the first snippet
public static void DelphiNetConsole()
{
System.IsConsole = true;
try
{
TextOutput.Output.WriteWideString("Hello From Delphi 2007.Net", 0).WriteLn();
System.#_IOTest();
}
catch (Exception exception1)
{
Exception exception2 = System.#ExceptObject = exception1;
Exception E = exception1;
TextOutput.Output.WriteWideString(TObjectHelper.ClassName(System.#GetMetaFromObject(E)), 0).WriteWideString(": ", 0).WriteWideString(E.Message, 0).WriteLn();
System.#_IOTest();
System.#ExceptObject = null;
}
}
As you can see the last code call a lot of helper classes and functions (like TextOutput) which are not part of the standard .net framework, rather they are part of the Borland.Delphi.System namespace.
Reflector can help you to translate some snippets of code but not the full application in an automated way.
The answer is no, and even if you deploy the corresponding Delphi assemblies, such as Borland.Delphi.dll and Borland.Vcl.dll, you have structures that have no equivalent in C#, such as class references, that cannot be used within Visual Studio/C#. I managed to convert about 80,000 lines of a non-visual application framework in Delphi to use in Visual Studio/C#, but it took me over 3 months and I had to convert code that used things like class references to use the System.Type class, amongst other things. After all this work, and with the deployment of some basic Delphi assemblies, an Indy assembly, and a Jcl assembly, I can now develop in either Delphi or Visual Studio and maintain communication compatibility between the two types of applications.
One other thing I did is to run some custom pre-processing of the source code before building to strip of the "T..." type prefix so that the actual framework assemblies look just like C# assemblies when used in Visual Studio. This was no easy task but was made possible by the fact that all types, constants, etc in my framework were ALL prefixed as well by either "Csi", "App", "Fwk", or "Dev". Without this I could not have stripped off the Deplhi-specific identifier naming conventions.
Unless there is an overwhelming benefit for doing this which outweighs the cost (like me), and your code is essentially non-visual (like me), the amount of effort involved is likely to be far too great to justify the work. I wonder if I am the only Delphi developer in the world to succesfully have migrated a significant amount of code from Delphi for use in Visual Studio. Nobody else seems to be able to provide a success story like this, which really makes you wonder how feasible this is.

C# Mersenne Twister random integer generator implementation (SFMT) monte carlo simulation

So far I've been using the C# Mersenne Twister found here to generate random numbers:
http://www.centerspace.net/resources.php
I just discovered SFMT which is supposed to be twice as fast here:
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/
Can anyone point me at a C# implementation of SFMT?
My requirements are to generate an integer between (and including) 0 and 2^20 (1048576).
I need to do this trillions of times everyday for a simulation running on a 24 hour clock so I am prepared to spend days tweaking this to perfection.
Currently I've tweaked the Center Space Mersenne Twister by adding a new method to fit my requirements:
public uint Next20()
{
return (uint)(genrand_int32() >> 12);
}
Using the method genrand_int32() I'd like to produce my own version, genrand_int20(), that generates an integer between (and including) 0 and 2^20 to save on the cast above and shift but I don't understand the mathematics. Exactly how can I do this?
Also is using an uint going to be faster that int, or is just a matter of addressable numbers? Because I only need up to 1048576, I am only concerned with speed.
Also this will be running on a Windows Server 2003 R2 SP2 (32bit) box with .NET 2. Processor is AMD Opteron 275 (4 core).
What you can do is download the source from the link you discovered on Code Project. Unzip it, load the solution in Visual Studio and compile it. This will give you source, an unmanaged c dll and a .lib file.
You can P/Invoke the functions in this dll, (there are only 5 simple functions exported, of which you need only two) or you can use this dll, lib, and the SFMT header file to create a managed wrapper dll you can use in C# without P/Invoke. I just tried this method and it was very simple to do. There was no explicit marshalling involved.
Here's how. Once you have downloaded and compiled the source (you need the header and the lib file that is created in addition to the dll) create a new C++ CLR Class Library project. Call it WrapSFMT or something. Go the project properties. Under C++/Precompiled Headers, change to "Not using precompiled headers." Under the Linker/General/Additional Library Directories, enter the path to the SFMT.lib. Under Linker/Input/Additional Dependencies, add SFMT.lib. Close the property pages. Copy SFMT.h to your project folder and include it in the project.
Edit WrapSFMT.h to read as follows:
#pragma once
#include "SFMT.H"
using namespace System;
namespace WrapSFMT {
public ref class SRandom
{
public:SRandom(UInt32);
public:UInt32 Rand32(void);
};
}
These declare the methods that will be in your class. Now edit WrapSFMT.cpp to read:
#include "WrapSFMT.h"
namespace WrapSFMT {
SRandom::SRandom(UInt32 seed)
{
init_gen_rand(seed);
}
UInt32 SRandom::Rand32()
{
return gen_rand32();
}
}
These implement the methods you declared in the header file. All you are doing is calling functions from the SFMT.dll, and C++/CLI is automatically handling the conversion from unmanaged to managed. Now you should be able to build the WrapSFMT.dll and reference it in your C# project. Make sure the SFMT.dll is in the path, and you should have no problems.
You can find a C# implementation of SFMT (plus other RNG algorithms) at...
http://rei.to/random.html
The page and source code comments are in Japanese but you should be able to figure it out.
You can also find a Google-translated version (to English) of the page at...
http://translate.google.com/translate?hl=en&sl=ja&u=http://rei.to/random.html
I don't really see your problem with speed here. On my machine (Core 2 Duo T7200 # 2 GHz) generating a random integer with MT19937 or MT19937-64 takes around 20 ns (on average, when drawing 50000 numbers). So that'd be around 4,32 × 1012 (so around 4 trillion numbers) a day. And that's for one core. With Java. So I think you can expect the performance to be more than adequate for your needs.
To actually answer your question: I don't know of a C# implementation of SFMT, but conversion of the C code to C# should be fairly straightforward. However, you're not gaining much, as SFMT is optimized for SIMD and C# currently doesn't support this directly.
Is there a reason you can't compile the C implementation into a DLL and call this from your C# code?
EDIT:
I'm sorry, but I have only a very limited knowledge of C (and indeed C#), but the "How to create a C dll" may be answered here: http://www.kapilik.com/2007/09/17/how-to-create-a-simple-win32-dll-using-visual-c-2005/ and the how fast can be checked by profiling the code.
Maybe this is what you're looking for?
There is a list of several implementations.
Specifically, this one (by Cory Nelson) might be useful.

Call C++ code from a C# application or port it?

I've recently been wrestling with an algorithm which was badly implemented (i.e. the developer was pulled off onto another project and failed to adequately document what he'd done) in C#.
I've found an alternative (from numerical recipes) which works but is written in C++. So I'm thinking probably the safest way to get something working would be to wrap the C++ up in a DLL.
Bearing in mind that I'm still a bit green when it comes to C# and have never tried making a DLL from scratch, does this sound like a reasonable approach (and if so, has anyone tried this / got any advice)? Or should I go the whole hog and try and port the C++ routine into C#?
Edit - I'm not looking for anyone to make the decision for me, but if anyone has any exprience of either route I'd be interested to hear their opinions and any nasty pitfalls that should be avoided. For example, how nasty is passing in lists of data from C# to a C++ STL vector?
I tried linking to c-dll's from c# code with quite good results, even though I had some problems sending data between the environments. Otherwise the procedure is quite straight forward. The more data you send back and forth (both amount and frequency) the slower your program will run, but you have probably already figured this out on your own.
The main drawback was maintaining the c#-c glue code (interface code) each time something changed or someone found a bug.
Here is a bit of code to get you started:
using System.Runtime.InteropServices;
class myDllCaller {
//call to function in the dll returning an int
[DllImport("MyFavorite.dll")]
private static extern int dllFunction(//list of parameters to function);
public static void Main() {
int rerult = dllFunction();
}
}
If the C# version Mitch references isn't of a suitable licence for your purposes, You could use a managed C++ wrapper, that could reuse, and wrap the C code you have, but still be visible to your managed applications as a native .Net assembly. I've used this approach in the past for using the C API of a library that didn't have its own native .Net API, and found it relatively painless marshalling data between the two.
It depends what your goals are.
If it's to have a working application I'd weigh-up the costs and benefits of both approaches and go with the most cost effective.
If it's to improve your C# then by all means rewrite the C.
...Or you could download the already implemented code in C# from here.

Which parsers are available for parsing C# code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Which parsers are available for parsing C# code?
I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code.
Works on source code:
CSParser:
From C# 1.0 to 2.0, open-source
Metaspec C# Parser:
From C# 1.0 to 3.0, commercial product (about 5000$)
#recognize!:
From C# 1.0 to 3.0, commercial product (about 900€) (answer by SharpRecognize)
SharpDevelop Parser (answer by Akselsson)
NRefactory:
From C# 1.0 to 4.0 (+async), open-source, parser used in SharpDevelop. Includes semantic analysis.
C# Parser and CodeDOM:
A complete C# 4.0 Parser, already support the C# 5.0 async feature. Commercial product (49$ to 299$) (answer by Ken Beckett)
Microsoft Roslyn CTP:
Compiler as a service.
Works on assembly:
System.Reflection
Microsoft Common Compiler Infrastructure:
From C# 1.0 to 3.0, Microsoft Public License. Used by Fxcop and Spec#
Mono.Cecil:
From C# 1.0 to 3.0, open-source
The problem with assembly "parsing" is that we have less informations about line and file (the informations is based on .pdb file, and Pdb contains lines informations only for methods)
I personnaly recommend Mono.Cecil and NRefactory.
Mono (open source) includes C# compiler (and of course parser)
If you are going to compile C# v3.5 to .net assemblies:
var cp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx
If you're familiar with ANTLR, you can use Antlr C# grammar.
I've implemented just what you are asking (AST Parsing of C# code) at the OWASP O2 Platform project using SharpDevelop AST APIs.
In order to make it easier to consume I wrote a quick API that exposes a number of key source code elements (using statements, types, methods, properties, fields, comments) and is able to rewrite the original C# code into C# and into VBNET.
You can see this API in action on this O2 XRule script file: ascx_View_SourceCode_AST.cs.o2 .
For example this is how you process a C# source code text and populate a number of TreeViews & TextBoxes:
public void updateView(string sourceCode)
{
var ast = new Ast_CSharp(sourceCode);
ast_TreeView.show_Ast(ast);
types_TreeView.show_List(ast.astDetails.Types, "Text");
usingDeclarations_TreeView.show_List(ast.astDetails.UsingDeclarations,"Text");
methods_TreeView.show_List(ast.astDetails.Methods,"Text");
fields_TreeView.show_List(ast.astDetails.Fields,"Text");
properties_TreeView.show_List(ast.astDetails.Properties,"Text");
comments_TreeView.show_List(ast.astDetails.Comments,"Text");
rewritenCSharpCode_SourceCodeEditor.setDocumentContents(ast.astDetails.CSharpCode, ".cs");
rewritenVBNet_SourceCodeEditor.setDocumentContents(ast.astDetails.VBNetCode, ".vb");
}
The example on ascx_View_SourceCode_AST.cs.o2 also shows how you can then use the information gathered from the AST to select on the source code a type, method, comment, etc..
For reference here is the API code that wrote (note that this is my first pass at using SharpDevelop's C# AST parser, and I am still getting my head around how it works):
AstDetails.cs
AstTreeView.cs
AstValue.cs
Ast_CSharp.cs
We have recently released a C# parser that handles all C# 4.0 features plus the new async feature: C# Parser and CodeDOM
This library generates a semantic object model which retains comments and formatting information and can be modified and saved. It also supports the use of LINQ queries to analyze source code.
You should definitely check out Roslyn since MS just opened (or will soon open) the code with an Apache 2 license here. You can also check out a way to parse this info with this code from GitHub.
http://www.codeplex.com/csparser
SharpDevelop, an open source IDE, comes with a visitor-based code parser which works really well. It can be used independently of the IDE.
Consider to use reflection on a built binary instead of parsing the C# code directly. The reflection API is really easy to use and perhaps you can get all the information you need?
Have a look at Gold Parser. It has a very intuitive IU that lets you interactively test your grammar and generate C# code. There are plenty of examples available with it and it is completely free.
Maybe you could try with Irony on irony.codeplex.com.
It's very fast and a c# grammar already exists.
The grammar itself is written directly in c# in a BNF like way (acheived with some operators overloads)
The best thing with it is that the "grammar" produces the AST directly.
Something that is gaining momentum and very appropriate for the job is Nemerle
you can see how it could solve it in these videos from NDC :
Igor Tkachev - Metaprogramming with Nemerle
Igor Tkachev - Nemerle Programming Language
Not in C#, but a full C# 2/3/4 parser that builds full ASTs is available with our DMS Software Reengineering Toolkit.
DMS provides a vast infrastructure for parsing, tree building, construction of symbol tables and flow analyses, source-to-source transformation, and regeneration of source code from the (modified) ASTs. (It also handles many other languages than just C#.)
EDIT (September) 2013: This answer hasn't been updated recently. DMS has long handled C# 5.0
GPPG might be of use, if you are willing to write your own parser (which is fun).

What is the best C# to VB.net converter? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
While searching the interweb for a solution for my VB.net problems I often find helpful articles on a specific topic, but the code is C#. That is no big problem but it cost some time to convert it to VB manually.
There are some sites that offer code converters from C# to VB and vice versa, but to fix all the flaws after the code-conversion is nearly as time-consuming as doing it by myself in the first place.
Till now I am using http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx
Do you know something better?
Telerik has a good converter that is based on SharpDevelop that has worked pretty well over the years, though it has not been updated in years (due to it being based on SharpDevelop).
I've recently come across a roslyn based converter as well. I don't know how well it works or how well maintained it is, but as it's open source you can always fork it and update it as needed.
If you cannot find a good converter, you could always compile the c# code and use the dissasembler in Reflector to see Visual Basic code. Some of the variable names will change.
I currently use these two most often:
http://converter.telerik.com/
http://www.carlosag.net/tools/codetranslator/
But have also had some success with these others:
http://converter.atomproject.net/
http://www.dotnetspider.com/convert/Csharp-To-Vb.aspx
http://www.developerfusion.com/tools/convert/csharp-to-vb/
SharpDevelop has a built-in translator between C# and VB.NET. Is not perfect thought (e.g. the optional values in VB.NET doesn't have an equivalent in C#, so the signature of the converter method must be edited), but you can save some time, as you are making all operations inside an IDE and not a webpage (copy C# code, paste, hit button, copy VB.NET code, paste on IDE :P )
I think the best thing to do is learn enough of the other language so that you can rewrite by hand, there's some quite difficult differences in certain aspects that I'm not sure a converter would handle very well. For example, compare my translation from C# to VB of the following:
public class FileSystemEventSubscription : EventSubscription
{
private FileSystemWatcher fileSystemWatcher;
public FileSystemEventSubscription(IComparable queueName,
Guid workflowInstanceId, FileSystemWatcher fileSystemWatcher) : base(queueName, workflowInstanceId)
{
this.fileSystemWatcher = fileSystemWatcher;
}
becomes
Public Class FileSystemEventSubscription
Inherits EventSubscription
Private myFileSystemWatcher As FileSystemWatcher
Public Sub New(ByVal QueueName As IComparable, ByVal WorkflowInstanceID As Guid, ByVal Watcher As FileSystemWatcher)
MyBase.New(QueueName, WorkflowInstanceID)
Me.myFileSystemWatcher = Watcher
End Sub
The C# is from the Custom Activity Framework sample, and I'm afraid I've lost the link to it. But it contains some nasty looking inheritance (from a VB point of view).
I am using a free Visual Studio 2012 plug-in named Language Convert
It works perfectly on 2010/2012, unfortunately isn't working at VS 2013 yet.
The conversion is not 100% accurate, but it is definitely very helpful, to launch for the first time it is a bit tricky, check before the image below :
Last I checked, SharpDevelop has one and it is open source too.
You can load your DLL or EXE into Redgate's (formerly Lutz Roeder's) .Net Reflector, select your method and then the desired language from the language combo. The code of the selected method will be displayed in the selected language.
I hope this helps.
You can try this one converter. There is functionality for C# to VB and VB to C#.
Hope this helps.
Carlos Aguilar Mares has had an online converter for about 40 forevers - Code Translator but I would agree that Reflector is the better answer.
While not answering your question, I will say that I have been in a similar position.
I realised that code samples in C# were awkward when I was really starting out in .NET, but a few weeks into my first project (after I grown more familiar with the .NET framework and VB.NET itself), I found that it was interesting and sometimes beneficial to have to reverse-engineer the C# code. Not just in terms of syntax, but also learning about the subtle differences in approach - it's useful to be open-minded in this respect.
I'm sticking with VB.NET as I learn more and more about the framework, but before long I'll dip my to into C# with the intention of becoming 'multi-lingual'.
Currently I use a plugin for VS2005 that I found on CodeProject (http://www.codeproject.com/KB/cs/Code_convert_add-in.aspx); it use an external service (http://www.carlosag.net/Tools/CodeTranslator/) to perform translation.
Occasionally, when I'm offline, I use a converter tool (http://www.kamalpatel.net/ConvertCSharp2VB.aspx).
The one at http://www.developerfusion.com/tools/convert/csharp-to-vb/ (new url) now supports .NET 3.5 syntax (thanks to the #develop guys once again), and will automatically copy the results to your clipboard :)

Categories

Resources