繁体   English   中英

使用CodeDom以编程方式编译c#windpws表单中的C代码?

[英]Programatically compile the C code in c# windpws forms using CodeDom?

我正在制作一个C编译器,我必须知道我是否可以使用CodeDom在c#中编译C代码,目前我正在使用编译c#windows形式的C#代码的代码?

有没有简单的方法来编译C语言的代码?

using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
private void button1_Click(object sender, System.EventArgs e)
{
   CSharpCodeProvider codeProvider = new CSharpCodeProvider();
   ICodeCompiler icc = codeProvider.CreateCompiler();
   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 = icc.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);
   }
}

你没有编译器。 你正在建立一个编译器的接口 不,你不能使用CodeDom 为什么不直接使用C编译器? 你可以用很多吨来达到这个目的。 捕获STDOUT - 编译器输出的格式有一般指导,解析它们应该是一个相当简单的任务。

您也可以尝试嵌入C解释器。 现在可能很有趣。 更有趣的是:编写自己的C解释器(比编译器更容易实现)。

我想你正在关注 - 如何使用C#编译器以编程方式编译代码

在为您的工作使用任意代码之前,请完整地了解它是否适​​合您的要求。 您正在使用的是.net框架内部编译助手类。 检查该文章的以下几行。

.NET Framework公开了允许您以编程方式访问C#语言编译器的类。 如果要编写自己的代码编译实用程序,这可能很有用。

和要求

  • 视觉工作室
  • Visual C#语言编译器

那么如何使用这些.net库类编译c program

您可以使用c编译器exe并使用该编译器,您可以在控制台应用程序中编译文件或使用.net中的Process类。

您可以从命令行编译c,只需使用c#中的相同内容, redirectstandardoutput将允许您获取将显示的输出。

Process proc = new Process();
proc.StartInfo.FileName = "compiler name";
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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