编译简单的字符串

jay*_*t55 8 c# c++ compiler-construction messagebox

只是想知道c ++或者c#中是否有任何内置函数可以让你在运行时使用编译器?例如,如果我想要翻译:

!print "hello world";
Run Code Online (Sandbox Code Playgroud)

成:

MessageBox.Show("hello world");
Run Code Online (Sandbox Code Playgroud)

然后生成一个exe,然后才能显示上面的消息?几年前我在网上看到过这样做的样本项目但是找不到它了.

Jam*_*mes 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;
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*kis 5

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