2

I am looking for a solution to compile and execute C++ code inside a C# program. Is there any way of doing that? I am using visual studio 2019 professional. The code below is to create C# compiler.

Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();

And I want to create C++ code and compile and execute it. I try this in my code:

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("Cpp");

but the error is:

System.Configuration.ConfigurationErrorsException: 'The CodeDom provider type "Microsoft.VisualC.CppCodeProvider, CppCodeProvider, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" could not be located.'

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("Cpp");
string Output = "Out.exe";
Button ButtonObject = (Button)sender;

textBox2.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = 
codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);

if (results.Errors.Count > 0)
{
    textBox2.ForeColor = Color.Red;
    foreach (CompilerError CompErr in results.Errors)
    {
        textBox2.Text = textBox2.Text +
                    "Line number " + CompErr.Line +
                    ", Error Number: " + CompErr.ErrorNumber +
                    ", '" + CompErr.ErrorText + ";" +
                    Environment.NewLine + Environment.NewLine;
    }
}
else
{
    //Successful Compile
    textBox2.ForeColor = Color.Blue;
    textBox2.Text = "Success!";
    //If we clicked run then launch our EXE
    if (ButtonObject.Text == "Run") Process.Start(Output);
}
AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52

1 Answers1

1

You may need to create a C++ project then compile it into DLL and use it inside your C# project.

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
  • I am working on a master project to porting ipv4 applications to ipv6 applications and the applications wrote in c++ I use c# to build the program of porting and I want to build and execute the ported code – Yaser Alajely Nov 03 '19 at 09:18
  • I think you can transform C++ code to C# and add it to your program, I did this before in my PhD thesis. – AbdelAziz AbdelLatef Nov 03 '19 at 15:59
  • can I get your thesis and use it as a reference? – Yaser Alajely Nov 03 '19 at 18:21
  • I don't think it will help you. However, I get this code https://github.com/ahmetozlu/vehicle_counting_hog_svm/blob/master/src/Main.cpp in C++ and converted it to C#, this shall be quite easy if you know both languages, the main challenge will be if an external library is used, then you will have to look for an equivalent in C#, for example in my case, OpenCV was used in C++ and I had to convert it to EmguCV. – AbdelAziz AbdelLatef Nov 04 '19 at 00:15