简体   繁体   中英

Compile and execute C++ code inside C# program

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM