使用 CodeDom 以编程方式编译 c#windpws 形式的 C 代码? [英] Programatically compile the C code in c# windpws forms using CodeDom?
问题描述
我正在制作一个 C 编译器,我必须知道我是否可以使用 CodeDom 在 c# 中编译 C 代码,目前我正在使用以下代码来编译 c# windows 形式的 C# 代码?
I am working on making a C compiler, I have to know if I can compile C code in c# using CodeDom, currently I am working wd following code that compiles the C# code in c# windows form?
有没有什么简单的方法可以编译C语言的代码?
Is there any easy way to compile C language's Code?
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
- 编译器输出的格式有一般准则,解析它们应该是一项相当简单的任务.
Your not making a compiler. You're making an interface to a compiler. No, you can't use CodeDom
for this. Why not just shell out to a C compiler? There are tons you could use for this purpose. Capture STDOUT
- there are general guidelines to the format of compiler outputs and parsing them should be a rather simple task.
您也可以尝试研究嵌入 C 解释器.现在那可能很有趣.更有趣的是:编写自己的 C 解释器(比编译器更容易实现).
You could also try looking into embedding a C interpreter. Now that could be interesting. Even more interesting: Write your own C interpreter (easier to pull off than a compiler).
这篇关于使用 CodeDom 以编程方式编译 c#windpws 形式的 C 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!