8

Was just wondering if there are any built in functions in c++ OR c# that lets you use the compiler at runtime? Like for example if i want to translate:

!print "hello world";

into:

MessageBox.Show("hello world");

and then generate an exe which will then be able to display the above message? I've seen sample project around the web few years ago that did this but can't find it anymore.

4

6 回答 6

16

可以使用 C#。查看 CodeProject 中的此示例项目

代码提取

private Assembly BuildAssembly(string code)
{
    Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider();
    ICodeCompiler compiler = provider.CreateCompiler();
    CompilerParameters compilerparams = new CompilerParameters();
    compilerparams.GenerateExecutable = false;
    compilerparams.GenerateInMemory = true;
    CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code);
    if (results.Errors.HasErrors)
    {
       StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
       foreach (CompilerError error in results.Errors )
       {
            errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
       }
       throw new Exception(errors.ToString());
    }
    else
    {
        return results.CompiledAssembly;
    }
}

public object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args)
{
    object returnval = null;
    Assembly asm = BuildAssembly(code);
    object instance = null;
    Type type = null;
    if (isstatic)
    {
        type = asm.GetType(namespacename + "." + classname);
    }
    else
    {
        instance = asm.CreateInstance(namespacename + "." + classname);
        type = instance.GetType();
    }
    MethodInfo method = type.GetMethod(functionname);
    returnval = method.Invoke(instance, args);
    return returnval;
}
于 2009-09-01T11:40:12.610 回答
5

在 C++ 中,您不能在运行时使用编译器,但可以在项目中嵌入解释器,例如CINT。

于 2009-09-01T11:36:02.197 回答
3

您始终可以使用 system() 并调用编译器“gcc ...”或等效的方式以肮脏的方式进行操作

于 2009-09-01T11:39:26.730 回答
1

Nick 的建议很好,但有一个替代方案可能更易于实施(但可能不适用于所有项目)。如果您可以假设您的用户安装了编译器,则可以生成一个文件,然后使用他们的编译器对其进行编译。

于 2009-09-01T11:42:08.270 回答
1

.NET 框架提供了一些类,可让您访问 C# 和 VB.NET 的编译器和代码生成器,从而将程序集加载到内存或简单的 .exe 文件。请参阅CSharpCodeProvider这篇文章

或者,您可以只创建源文件并手动编译它们(命令行调用 ( system) 到编译器、makefile)。

关于源代码的翻译:您必须在这里使用正则表达式之类的解析机制,或者使用 Coco/R、yacc 等编译器-编译器工具。(请注意,在 C++ 下,boost::spirit也很有用)

于 2009-09-01T11:42:29.877 回答
1

在 C# 中,您可以创建一个 .NET “CodeDom”树,然后使用 .NET 编译器对其进行编译。这使您可以完全访问 .NET 的大多数功能。

有关详细信息,请参阅 CodeCompileUnit 的“System.CodeDom”命名空间或MSDN 帮助

于 2009-09-01T11:43:06.787 回答