For the experiment, I try to read the body of the method (using GetILAsByteArray () ) from the source type and adding it to the new type (using CreateMethodBody () ).
My source class is just
public class FullClass { public string Test(string data) { return data; } public string Test2(string data) { return data; } public string Test5(string data, string data1) { return data + data1; } }
IL generated for this code (using reflector)
.method public hidebysig instance string Test(string data) cil managed { .maxstack 1 .locals init ( [0] string CS$1$0000) L_0000: nop L_0001: ldarg.1 L_0002: stloc.0 L_0003: br.s L_0005 L_0005: ldloc.0 L_0006: ret }
But the IL generated from my new type looks like this:
.method public hidebysig virtual instance string Test(string) cil managed { .maxstack 0 L_0000: nop L_0001: ldarg.1 L_0002: stloc.0 L_0003: br.s L_0005 L_0005: ldloc.0 L_0006: ret }
Differences are the meaning of maxstack and .locals. I do not understand why my actual class generates locals, although it does not have any local variables
And why are there differences in the value of .maxstack, since I use the same IL from the source to create a new type.?
Because of this, I get the error "Common Language Runtime detected an invalid program when calling a method.
My code creating a dynamic type is as follows
public static class Mixin<Target> { public static Target compose<TSource>() { Type newType = null; AppDomain currentDom = Thread.GetDomain(); AssemblyName DAssembly = new AssemblyName(); DAssembly.Name = "DynamicTypesAssembly"; AssemblyBuilder DAssemblyBldr = currentDom.DefineDynamicAssembly( DAssembly, AssemblyBuilderAccess.RunAndSave); ModuleBuilder DModuleBldr = DAssemblyBldr.DefineDynamicModule(DAssembly.Name, DAssembly.Name + ".dll", false);
And the code to call this
var resMix = Mixin<ITest>.compose<FullClass>(); var returned1 = resMix.Test("sam");
Edit: And the ITest interface (Target)
public interface ITest { string Test(string data); }
EDIT:
when commenting on this line
maxstack becomes .maxstack 16
I checked the check against the new dll against the PEverify tool, this gives the following error
WorkOut.DType :: Test] [offset 0x00000002] Unrecognized local variable number.
Any help really appreciated .... :)