编译简单字符串 [英] Compile simple string

查看:89
本文介绍了编译简单字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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";

进入:

MessageBox.Show("hello world");

然后生成一个exe文件,它将能够显示以上消息?几年前,我已经在网上看到了一个示例项目,但是却找不到了.

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.

推荐答案

可以使用C#.看看CodeProject中的这个示例项目.

It is possible using C#. Have a look at this Sample Project from the 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;
}

这篇关于编译简单字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆