How to fix a method with a preloaded local variable MethodInfo?

I would like to emit a method that has a variable that I can do. But I would like to store a MethodInfo object in this variable, which is a reference to another (not emitted) method.

I could generate operation codes for calling typeof (someClass) .GetMethod (...), but it would be more efficient if I could just load the token for this MethodInfo and bake it directly in the variable.

So, to rephrase, I'm trying to figure out, from its possible emission, say, the operation code "load object" and pass it an object at the time of emit-time, which will be loaded onto the stack at runtime. (OpCodes.Ldobj gave some kind of error when I tried this). Or am I forced to emit opcodes that will do this at runtime?

+5
source share
1 answer

You cannot simply load any shared object into IL, because there is no way to store it in IL (with the exception of some special types, such as string). You can get around this using serialization (for types that support it), but I don't think you want to. It also ldobjserves a completely different purpose.

MethodInfo , , # typeof. :

, MethodInfo, :

MethodInfo loadedMethod = …;
var getMethodMethod = typeof(MethodBase).GetMethod(
    "GetMethodFromHandle", new[] { typeof(RuntimeMethodHandle) });

var createdMethod = new DynamicMethod(
    "GetMethodInfo", typeof(MethodInfo), Type.EmptyTypes);

var il = createdMethod.GetILGenerator();
il.Emit(OpCodes.Ldtoken, loadedMethod);
il.Emit(OpCodes.Call, getMethodMethod);
il.Emit(OpCodes.Castclass, typeof(MethodInfo));
il.Emit(OpCodes.Ret);

var func = (Func<MethodInfo>)createdMethod.CreateDelegate(typeof(Func<MethodInfo>));
Console.WriteLine(func());
+8

All Articles