学習/実験用のおもちゃのコンパイラを作りました。
C# コードをコンパイルするためのコードを次に示します。
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
namespace ProgrammingSystem
{
public class Compiler
{
public Program Compile(Code code)
{
string template = @"
public class C
{
public static void Main(string[] args)
{
[[Source]]
}
}";
string source = template.Replace("[[Source]]", code.Source);
CodeDomProvider compiler = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.WarningLevel = 4;
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
CompilerResults r = compiler.CompileAssemblyFromSource(parameters, source);
foreach (var item in r.Output)
this.Fire(Output, item);
Assembly assembly = r.CompiledAssembly;
return new Program(assembly);
}
public event EventHandler<OutputEventArgs> Output;
}
}
そして、コピーされたコードを実行するためのコードは次のとおりです。
using System;
using System.Reflection;
namespace ProgrammingSystem
{
public class Program
{
private System.Reflection.Assembly assembly;
public Program(System.Reflection.Assembly assembly)
{
this.assembly = assembly;
}
public event EventHandler<OutputEventArgs> ProgramOutput;
public void Run()
{
Type[] types = this.assembly.GetTypes();
Type programType = types[0];
MethodInfo programMainMethod = programType.GetMethod("Main");
programMainMethod.Invoke(null, new object[] { new string[] { } });
this.Fire(ProgramOutput, "hello");
}
}
}
CSharpCodeProviderによって実行時に生成される型とどのような方法で通信できますか?
具体的には、パブリック デリゲートをサブスクライブするか、標準出力をキャプチャすることに関心がありますが、このような状況で型がどのように相互に通信できるかについての一般的な情報で十分です。