c# - 使用 CodeDom 以编程方式编译 C# Windows 窗体中的 C 代码?

标签 c# c winforms

我正在制作一个 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);
   }
}

最佳答案

您没有制作编译器。您正在为编译器创建一个接口(interface)。不,您不能为此使用 CodeDom。为什么不直接使用 C 编译器呢?有很多东西可以用于此目的。捕获 STDOUT - 编译器输出格式有一般准则,解析它们应该是一项相当简单的任务。

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

关于c# - 使用 CodeDom 以编程方式编译 C# Windows 窗体中的 C 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10832307/

相关文章:

c# - 如何对类列表进行排序

c# - 如何将 ArrayList 转换为结构数组?

c# - WaveOut 将波形文件播放到设备的特定 channel

C - 未引用的 Omp 函数

c - 为accept()系统调用工作

.net - Tabcontrol:如何删除标签页标题?

C# WinForms trayapp MenuItem 鼠标悬停检测

c# - Redis快速插入5000万条记录的方法

c# - 检查二维数组的对角线 - 欧拉数 11

c - 需要一个 union 来从 20 个字符生成 5 个整数