Open Emitted assembly generated code appears empty in Reflector when it is not.
Asked Answered
C

1

7

I'm generating a dynamic assembly using Reflection.Emit which includes a single class. I have a bug which is causing a BadImageException. To resolve this I need to see the compiled code, and therefore I'm saving the dynamic assembly to disk.

I've already tried PEVerify against the assembly which seems to think there are no errors. I now want to view the generated code in Reflector, but the assembly appears as empty (which I know it's not).

Any idea why this is happening?

var assemblyName = new AssemblyName("An.Assembly");
var appDomain = Thread.GetDomain();
var assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
var typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public | TypeAttributes.Class);
... 
typeBuilder.CreateType();
assemblyBuilder.Save("temp.dll");

By the way I'm already using the Relection.Emit plugin for reflector which doesn't help with this issue.

Chilcote answered 18/10, 2010 at 20:7 Comment(4)
BadImageFormatException? That's bizarre. Document the exception better, message + stack trace.Stipulate
Is it empty when you look at it with ildasm as too?Carnes
No it's BadImageException caused by some error in the emitting of IL code. Even if I revert my code so that it doesn't throw the exception, I'm still unable to view emitted code in Reflector.Chilcote
Yes it's empty with ildasm too. Not sure what I'm missing.Chilcote
E
15

Replace:

var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

With:

var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, "yourfilename.dll");

Then look for it in your current directory, probably your bin folder. Assemblies and modules are technically two separate entities, and you're only saving the assembly information, not the module information (where all your code lives). (Also, don't name them both with the same filename, of course.)

Erythritol answered 18/10, 2010 at 20:19 Comment(3)
This makes no difference, in either case the file is written out.Chilcote
@TheCodeKing, did you try it? In either case, the file is written out, but, importantly, not the same file contents.Erythritol
sorry I take it back, I was still opening the temp.dll but it's actually created another assembly called "an.assembly.dll" which does contain the code! Thank you very much, I spent a long time trying to figure this one out.Chilcote

© 2022 - 2024 — McMap. All rights reserved.