I remember when .NET 4 was in beta there was a video of a developer that made a command-line app that he could type C# code into and it would compile the code on the fly. The idea was that the compiler was now available in the .NET language.
Anyone recall where this is? I need to create an application with a small macro language and I would love to use C# as that macro language, but I don't know where to find this library..
You can use the CSharpCodeProvider
class to compile assemblies at runtime.
You'll need to make a boilerplate template to wrap the macro commands in a static method in a class.
For example:
static readonly Assembly[] References = new[] { typeof(Enumerable).Assembly, typeof(Component).Assembly };
public Action CompileMacro(string source) {
var options = new CompilerParameters(References.Select(a => a.Location).ToArray()) {
GenerateInMemory = true
};
string fullSource = @"public static class MacroHolder { public static void Execute() { \r\n" + source + "\r\n} }";
try {
var compiler = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });
var results = compiler.CompileAssemblyFromSource(options, fullSource);
if (results.Errors.Count > 0)
throw new InvalidOperationException(String.Join(
Environment.NewLine,
results.Errors.Cast<CompilerError>().Select(ce => ce.ErrorText)
));
return (Action)Delegate.CreateDelegate(
typeof(Action),
results.CompiledAssembly.GetType("MacroHolder").GetMethod("Execute")
);
} finally { options.TempFiles.Delete(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With