Saving a DynamicMethod to disk
Asked Answered
S

2

6

I have inherited code that uses DynamicMethod to generate methods at runtime. I also need to modify some of the code that is being generated.

Since I am a n00b at MSIL, I would love to be able to load the generated code up in Reflector and ensure that the code does what I pray that it does ;)

Only, I can't figure out how to serialize the "Anonymously Hosted DynamicMethods Assembly" to disk. Is this possible? If so, how?

Soothsayer answered 14/6, 2011 at 19:59 Comment(0)
P
3

I think that if you want to load the method in Reflector or dotPeek, you need to create an actual assembly. To do this, use MethodBuilder instead of DynamicMethod. Most of the usage of them should be the same.

Polled answered 14/6, 2011 at 22:25 Comment(1)
Sorry to keep this open for so long. I wanted to wait until I could implement this before I accepted, but of course I'm working on another project now! Still, this seems like the only real answer, so when I get back to working on this, I'll know what to do.Soothsayer
A
9

Try this,

  var assemblyName = new AssemblyName("SomeName");
  var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, @"c:");
  var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name +  ".dll");

  TypeBuilder builder = moduleBuilder.DefineType("Test", TypeAttributes.Public);
  var methodBuilder = builder.DefineMethod("DynamicCreate", MethodAttributes.Public, typeof(T), new[] { typeof(IDataRecord) }); 
  /* this line is a replacement for your  new DynamicMethod(....)  line of code

  /* GENERATE YOUR IL CODE HERE */

  var t = builder.CreateType();
  assemblyBuilder.Save(assemblyName.Name + ".dll");
Aviator answered 6/7, 2011 at 9:16 Comment(0)
P
3

I think that if you want to load the method in Reflector or dotPeek, you need to create an actual assembly. To do this, use MethodBuilder instead of DynamicMethod. Most of the usage of them should be the same.

Polled answered 14/6, 2011 at 22:25 Comment(1)
Sorry to keep this open for so long. I wanted to wait until I could implement this before I accepted, but of course I'm working on another project now! Still, this seems like the only real answer, so when I get back to working on this, I'll know what to do.Soothsayer

© 2022 - 2024 — McMap. All rights reserved.