forked from den-run-ai/clrmagic
-
Notifications
You must be signed in to change notification settings - Fork 1
/
clrmagic.cs
56 lines (49 loc) · 1.97 KB
/
clrmagic.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
namespace MagicIPython
{
public static class MagicCS
{
private const string embedCode = @"
namespace MagicCSIPython
{0}
public static class MagicCSFunctions_{2}
{0}
{3}
{1}
{1}
";
public static MethodInfo CreateFunction(string functionName, string code, string[] dependencies)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
if (dependencies != null) {
foreach (var d in dependencies)
parameters.ReferencedAssemblies.Add(d);
}
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
code = string.Format(embedCode, "{", "}", functionName, code);
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
if (results.Errors.HasErrors) {
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors) {
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
}
throw new InvalidOperationException(sb.ToString());
}
Type binaryFunction = results.CompiledAssembly.GetType(string.Format("MagicCSIPython.MagicCSFunctions_{0}", functionName));
return binaryFunction.GetMethod(functionName);
}
public static object RunFunction(MethodInfo function, object[] parameters)
{
return function.Invoke(null, parameters);
}
}
}