jeudi 16 avril 2020

C# - Get method pointer from generated method from expression.Compile()

I get the pointer of a method with the following:

public unsafe static long* GetPointer(MethodInfo info)
{
    // Simplified method without any checks    
    // if(IntPtr.Size == 4){ return (int*)info.MethodHandle.Value.ToPointer() + 2; }
    return (long*)info.MethodHandle.Value.ToPointer() + 1;
}


Func<string, int> func = x => 102;
var pointer = GetPointer(func.Method); // Works

But if I want the pointer of a generated method from a lambda expression with expression.Compile() like the following snippet, I get the following error:

The requested operation is invalid for DynamicMethod

Expression<Func<string, int>> expression = x => 102;
Func<string, int> func2 = expression.Compile();
var pointer = GetPointer(func2.Method); // Fails

If I debug GetPointer, I get the following information for the MethodHandle-attribute:

MethodHandle = '((System.Reflection.Emit.DynamicMethod.RTDynamicMethod)info).MethodHandle' threw an exception of type 'System.InvalidOperationException'

Does anyone know how to get the pointer of a generated method? In the end, I want to replace the body of a method with the body of another method. The method to replace the body is adopted from the SO answer here.





Aucun commentaire:

Enregistrer un commentaire