How to do OpCodes.Call properly?

425 Views Asked by At

I'm practicing DynamicMethod from this post, and it all worked fine with the following little codes:

    private delegate long squareDel(int a);
    squareDel test;

    private void Form1_Load(object sender, EventArgs e)
    {
        DynamicMethod dm = new DynamicMethod("", typeof(long), new Type[] { typeof(int) },typeof(Form1));
        ILGenerator ig = dm.GetILGenerator();

        ig.Emit(OpCodes.Ldarg_0);
        ig.Emit(OpCodes.Conv_I8);
        ig.Emit(OpCodes.Dup);
        ig.Emit(OpCodes.Mul);
        ig.Emit(OpCodes.Ret);

        test = (squareDel)dm.CreateDelegate(typeof(squareDel));
`  `}

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(test(int.Parse(textBox1.Text)).ToString());
    }

But now I'm trying to incorporate it with OpCodes.Call with a little method:

    public long Test(int s)
    {
        return s*s;
    }

and do the following change to the code:

        MethodInfo mi = typeof(Form1).GetMethod("Test",new Type[] { typeof(int) });

        ig.Emit(OpCodes.Ldarg_0);
        ig.EmitCall(OpCodes.Call, mi,null);
        ig.Emit(OpCodes.Dup);
        ig.Emit(OpCodes.Mul);
        ig.Emit(OpCodes.Ret);

And now it keeps throwing me System.InvalidProgramException.

I went looking up the exception online and tried to change my build properties from this post to no avail.

And I can't find the so-called "Advanced Settings" from this post, so I assume that this post is out of date (it's from 5 years ago after all).

So could somebody PLEASE be so kind and teach me how to fix it?

Much appreciated!

0

There are 0 best solutions below