Reputation: 22406
I get the error when I run this code:
var asmName = new AssemblyName("DynamicAssembly");
var asmBuilder = AssemblyBuilder.DefineDynamicAssembly
(asmName, AssemblyBuilderAccess.Run);
var moduleBuilder = asmBuilder.DefineDynamicModule("DynamicModule");
var typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);
var methodBuilder = typeBuilder.DefineMethod("DynamicMethod", MethodAttributes.Static, typeof(double), new[] { typeof(double), typeof(double), typeof(double) });
myexp.Lambda.CompileToMethod(methodBuilder);
asmBuilder.SetEntryPoint(methodBuilder);
MethodInfo barMethod = asmBuilder.EntryPoint;
result = barMethod.Invoke(null, new object[] { 50d, 1d, 3d });
I get the error on the last line
The invoked member is not supported in a dynamic module.
I just want to call the method.
I added
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
to my app.config
to no avail.
Upvotes: 2
Views: 2758
Reputation: 3221
As @thehennyy pointed out in comment you should call typeBuilder.CreateType()
before invoking method, but calling Invoke
from methodBuilder
cause same error.
I've managed to call method after getting it from created type like this:
var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);
Here is complete code that I've used:
Expression<Func<double, double, double, double>> myexp = (a, b, c) => a * b * c;
var methodName = "DynamicMethod";
var asmName = new AssemblyName("DynamicAssembly");
var asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
var moduleBuilder = asmBuilder.DefineDynamicModule("DynamicModule");
var typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);
var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Static, typeof(double), new[] { typeof(double), typeof(double), typeof(double) });
myexp.CompileToMethod(methodBuilder);
var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);
asmBuilder.SetEntryPoint(method);
MethodInfo barMethod = asmBuilder.EntryPoint;
var result = barMethod.Invoke(null, new object[] { 50d, 1d, 3d });
Upvotes: 4