Is it possible to call OpCodes.Jmp to transfer control to a method that is on a different assembly?

Can Method 1, which is in AssemblyA, release OpCodes.Jmp to Method1, which is in AssemblyB? Both methods have the same exact signature.

I cannot get this to work, always getting System.InvalidProgramException: The Common Language Runtime encountered an invalid program.

If the redirection is inside the same assembly, it works.

If possible, please provide an example with Reflection.Emit.

+3


source to share


1 answer


You must have missed something. Are both methods static? Do they have the same agreement?

The following code doesn't reproduce your problem:

static void Main(string[] args)
{
    var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly
                    (new AssemblyName("TestAssembly"), AssemblyBuilderAccess.Run);
    var module = assembly.DefineDynamicModule("Main");
    var type = module.DefineType("Test");

    var method = type.DefineMethod
                  (
                    "Test", MethodAttributes.Public | MethodAttributes.Static, 
                    typeof(int), new[] { typeof(string) }
                  );
    var gen = method.GetILGenerator();
    gen.Emit(OpCodes.Jmp, typeof(Class1).GetMethod("Test"));

    var obj = Activator.CreateInstance(type.CreateType());

    var func = (Func<string, int>)
                obj.GetType().GetMethod("Test").CreateDelegate(typeof(Func<string, int>));
    var result = func("Banana");

    Console.WriteLine(result);
    Console.ReadLine();
}

      

And in another assembly, the class Test

:



public static class Class1
{
    public static int Test(string hi)
    {
        return 42;
    }
}

      

Are you sure you are not breaking any restrictions?

  • The evaluation stack must be empty while executing this instruction.
  • The calling convention, the number and type of arguments at the target address must match the name of the current method.
  • The jmp command cannot be used to transfer a control from a try, filter, catch, or finally file.
+5


source







All Articles