ILGenerator: load creation method

I am using System.Reflection.Emit, and at some point I want to create a delegate from MethodBuilder:

MethodBuilder fooBuilder = createFooMethodBuilder();
ILGenerator ilGenerator = ...
Type delegateType = typeof(DelegateType);
LocalBuilder delegateVar = ilGenerator.DeclareLocal(delegateType);
//Somehow create emit instructions to create delegate from fooBuilder
//Store delegate in delegateVar using 

I could find out that something like this is used to create delegates from static functions:

ldnull 
ldftn void class Test.MainClass::bar()
newobj instance void class Test.DelegateType::'.ctor'(object, native int)

But now I'm stuck. I need the ldftn MethodBuilder method, and then I need a way to fix the instruction for the next line. And I have no idea how to get a constructor that accepts its own int.

Any suggestions?

+3
source share
2 answers

A native intis IntPtrin C #.

You can get ConstructorInfofor the delegate type using Type.GetConstructor:

var constructorInfo =
    delegateType.GetConstructor(new Type[] { typeof(object), typeof(IntPtr) });

IL :

il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ldftn, someMethodInfo);
il.Emit(OpCodes.Newobj, constructorInfo);
+6

ILGenerator Emit, info, - ilGenerator.Emit(Opcodes.ldftn, mi), mi - , . , API- , , MethodBuilder ( MethodInfo).

, , newobj, ConstructorInfo .

0

Source: https://habr.com/ru/post/1778640/


All Articles