c# - How Do I make a Dynamically Compiled Class emit to a DLL -
i have data uses create program. purposes of example generated code:
using system; namespace mynamespace { public class builtprogram{ public bool eval(int x, int y, int z, out int ret) { console.writeline("test"); ret = x + y + z; return true; } } }
the code use generate following:
var factory = new programfactory(tree); var newprogram = factory.getcompiledprogram(); // program parsing code... syntaxtree programsyntaxtree = syntaxtree.parsetext(newprogram); var outputfile = "compiled.dll"; var compilation = compilation.create(outputfile, options: new compilationoptions(outputkind.dynamicallylinkedlibrary), syntaxtrees: new[] { programsyntaxtree } ); filestream file; using (file = new filestream(outputfile, filemode.create)) { emitresult result = compilation.emit(file); } // code breaks: assembly assembly = assembly.loadfile(file.name); type type = assembly.gettype("builtprogram"); var obj = activator.createinstance(type); int ret = 0; type.invokemember("eval", bindingflags.default | bindingflags.invokemethod, null, obj, args: new[] { (object)5, (object)10, (object)2, ret } );
it breaks on assembly line because says doesn't have assembly manifest, @ "compiled.dll" , there no data in it. doing wrong?
you have add reference mscorlib.
this make work:
var compilation = compilation.create(outputfile, options: new compilationoptions(outputkind.dynamicallylinkedlibrary), syntaxtrees: new[] { programsyntaxtree }, references: new [] { new metadatafilereference(typeof(object).assembly.location) } );
while accesing type, add namespace.
type type = assembly.gettype("mynamespace.builtprogram");
you may have difficulty getting out parameter value. see this.
Comments
Post a Comment