-
-
Save TheOtherBlack/2426a91ed521ad78c38f94e478cc7441 to your computer and use it in GitHub Desktop.
LowLevel Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection.Emit; | |
class Program | |
{ | |
public delegate int Add_dt(int a, int b, int c); | |
public static int Add(int a, int b, int c) | |
{ | |
return a + b + c; | |
} | |
static void Main(string[] args) | |
{ | |
var method = new DynamicMethod("CustomAdd", typeof(int), new[] { typeof(int), typeof(int), typeof(int) }); | |
var il = method.GetILGenerator(); | |
il.Emit(OpCodes.Ldarg_0); // Load A Parameter | |
il.Emit(OpCodes.Ldarg_1); // Load B Parameter | |
il.Emit(OpCodes.Add); // Pop both two parameters above off the stack and add the result to the stack! | |
il.Emit(OpCodes.Ldarg_2); // Load C Parameter | |
il.Emit(OpCodes.Add); // Add up both the Result of A + B and C together | |
il.Emit(OpCodes.Ret); // Return the result! | |
// We need to use a delegate type so we can cast our Delegate to the function type we want! | |
var customAdd = (Add_dt)method.CreateDelegate(typeof(Add_dt)); | |
int a = 44, b = 55, c = 66; | |
Console.WriteLine("Compiled Add Method:"); | |
Console.WriteLine("{0} + {1} + {2} = {3}", a, b, c, Add(a, b, c)); | |
Console.WriteLine("Runtime Emitted Add Method:"); | |
Console.WriteLine("{0} + {1} + {2} = {3}", a, b, c, customAdd(a, b, c)); | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment