Reputation: 327
It is possible to call a method that resides on a "Normal" assembly from a dynamically constructed assembly?
For example, assembly B is dynamically constructed(via Emit) from assembly A and assembly B needs to call a static method that is defined on assembly A.
public interface IMapper
{
void Map();
}
public void CreateDynamic() {
AppDomain app = AppDomain.CurrentDomain;
AssemblyName name = new AssemblyName("assemblyB");
AssemblyBuilder assembly = app
.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly
.DefineDynamicModule(assembly.GetName().Name, "b.dll");
TypeBuilder type = module.DefineType("MyType",
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AutoLayout, null, new[] {typeof (IMapper)});
MethodBuilder method = type
.DefineMethod("Map",
MethodAttributes.Public |
MethodAttributes.HideBySig |
MethodAttributes.Virtual);
ILGenerator il = method.GetILGenerator();
Func<int, TimeSpan> func = i => TimeSpan.FromSeconds(i);
il.Emit(OpCodes.Ldc_I4_S, 10);
il.Emit(OpCodes.Callvirt, func.Method);
il.Emit(OpCodes.Ret);
Type t = type.CreateType();
IMapper mapper = (IMapper) Activator.CreateInstance(t);
mapper.Map();
}
When the Map method is executed a MissingMethodExcetion is thrown and I do not now the reason for that.
Upvotes: 2
Views: 115
Reputation: 11549
Below line causes a private static
method to be created in the class at compile time.
Func<int, TimeSpan> func = i => TimeSpan.FromSeconds(i);
So what you are trying to do becomes something like this.
public class TestClass {
private static TimeSpan CompilerGeneratedMethod(int i) {
return TimeSpan.FromSeconds(i);
}
public void CreateDynamic() {
// Other codes...
var methodInfo = typeof(TestClass).GetMethod("CompilerGeneratedMethod", BindingFlags.Static | BindingFlags.NonPublic);
il.Emit(OpCodes.Ldc_I4_S, 10);
il.Emit(OpCodes.Callvirt, methodInfo);
il.Emit(OpCodes.Ret);
// Other codes...
}
}
Now we just created a class in AssemblyB that is trying to call a private static
method in another assembly. If it was directly written in C# it may look something like this.
public class MyType : IMapper {
public void Map() {
TestClass.CompilerGeneratedMethod(10);
}
}
Since the CompilerGeneratedMethod
is private
it cannot be accessed. So rather than using a lamda, let's try using a real declared public
method.
public class TestClass {
public static TimeSpan HandWrittenMethod(int i) {
return TimeSpan.FromSeconds(i);
}
public void CreateDynamic() {
// Other codes...
var methodInfo = typeof(TestClass).GetMethod("HandWrittenMethod");
il.Emit(OpCodes.Ldc_I4_S, 10);
il.Emit(OpCodes.Callvirt, methodInfo);
il.Emit(OpCodes.Ret);
// Other codes...
}
}
Now we have one minor problem. We are trying to call a static method using Callvirt
which should be used for late-bound methods. Instead of Callvirt
we should be using just Call
.
il.Emit(OpCodes.Call, methodInfo);
Upvotes: 1