From Schmid.wiki
Jump to: navigation, search
using System;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

class MetaProgram {

    delegate float ScalarFunction(float t);

    static void Main(string[] args) {

	// create method that evaluates expression given by args[0]
	ScalarFunction f = createMethod(args[0]);

	// evaluate a sequence of values
	for(float t = 0f; t <= 1f; t += 0.1f) {
	    Console.WriteLine( f(t) );
	}
    }

    static ScalarFunction createMethod(string expression) {
	CSharpCodeProvider codeProvider = new CSharpCodeProvider();

	CompilerParameters cp = new CompilerParameters();
	cp.GenerateExecutable = false;
	cp.GenerateInMemory = true;

	string ModuleSource = "class RuntimeGeneratedClass { " +
	    "public static float Evaluate(float t) { return (float)(" +
	    expression + ");}} ";

	CompilerResults cr = codeProvider.CompileAssemblyFromSource(cp, ModuleSource);

	if (cr.Errors.Count > 0) {
	    throw new ArgumentException(
		    string.Format("Expression cannot be evaluated: {0}",
		    cr.Errors[0].ErrorText));
	}
	else {
	    MethodInfo methodinfo =
		cr.CompiledAssembly.GetType("RuntimeGeneratedClass").GetMethod("Evaluate");

	    return Delegate.CreateDelegate(typeof(ScalarFunction), methodinfo)
		as ScalarFunction;
	}
    }
}