IL Return to C # returns an invalid value

I started rewriting my Function Plotter, which takes a math function and calculates the y value for a given x. To overwrite it, I want to dynamically create a method using IL. The IL test code I have now uses 2 LocalBuilders and multiplies them. However, when I return the value, I get (what seems) a random number instead of the real answer.

Here is the following code I used.

        ILGenerator il = hello.GetILGenerator();

        LocalBuilder a = il.DeclareLocal(typeof(int));
        LocalBuilder b = il.DeclareLocal(typeof(int));
        LocalBuilder multOfAandB = il.DeclareLocal(typeof(int));

        il.Emit(OpCodes.Ldc_I4, 5); // Store "5" ...
        il.Emit(OpCodes.Stloc, a);  // ... in "a".

        il.Emit(OpCodes.Ldc_I4, 6); // Store "6" ...
        il.Emit(OpCodes.Stloc, b);  // ... in "b".

        il.Emit(OpCodes.Ldloc, a);
        il.Emit(OpCodes.Ldloc, b); 

        il.Emit(OpCodes.Mul);       // Multiply them ...
        il.Emit(OpCodes.Ret);       // ... and return the result.

This should return 30, but currently I'm getting 4.2038953929744512E-44. Is there something wrong with my code that causes the function to return the wrong value?

Thanks in advance

EDIT

The code calling the function is as follows:

        object[] invokeArgs = { 42 };
        object obj = func.helloMethod.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));

, , func.helloMethod, DynamicMethod, :

DynamicMethod hello = new DynamicMethod("Hello",
            typeof(double),
            helloArgs,
            typeof(double).Module);
+4
2

, int double. , , .

:

var hello = new DynamicMethod(
    "Hello",
    typeof(int),
    helloArgs,
    typeof(YourClassNameHere).Module
);

, , .

+3

DynamicMethod:

DynamicMethod hello = new DynamicMethod("Hello",
        typeof(double),
        helloArgs,
        typeof(double).Module);

6 * 5 30, int, int double . typeof (int), 30. , IL .

+1

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


All Articles