0

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!

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
PiggyChu001
  • 440
  • 6
  • 20
  • 3
    this is because Test method is not static ...if it would ... obviously `ig.Emit(OpCodes.Ldarg_0); ig.EmitCall(OpCodes.Call, mi,null); ig.Emit(OpCodes.Ret);` should do the thing – Selvin Dec 19 '20 at 16:03
  • @Selvin WOW! That solved it! Who would ever thought!? Or just because my lack of knowledge. XD Thanks! Could you please be so kind and post it as an answer so I could mark it as the best answer? Much appreciated! – PiggyChu001 Dec 19 '20 at 16:07

0 Answers0