Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile simple string

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.

like image 673
jay_t55 Avatar asked Sep 01 '09 11:09

jay_t55


2 Answers

It is possible using C#. Have a look at this Sample Project from the CodeProject.

Code Extract

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;
}
like image 77
James Avatar answered Oct 07 '22 18:10

James


In C++ you can't use the compiler at runtime but you can embed an interpreter in your project, like CINT.

like image 20
Nick Dandoulakis Avatar answered Oct 07 '22 19:10

Nick Dandoulakis