static void Main() { Assembly assembly = CSScript.LoadCode( @"using System; public class Calculator : ICalculator { public int Add(int a, int b) { return a + b; } public string Join(string a, string b) { return a + b; } }"); AsmHelper calc = new AsmHelper(assembly); object instance = calc.CreateObject("Calculator"); //calc.CreateObject("*") can be used too if assembly has only one class defined FastInvokeDelegate methodInvoker = calc.GetMethodInvoker("Calculator.Add", 0, 0); int numOfLoops = 1000000; TestReflection(numOfLoops, calc, instance); TestFastInvoking(numOfLoops, calc, instance); TestDelegates(numOfLoops, methodInvoker, instance); TestInterface(numOfLoops, instance); TestInterfaceAlignment(numOfLoops, instance); TestDynamic(numOfLoops, instance); TestCompiledCode(numOfLoops); TestCompiledDelegate(numOfLoops); //TestMethodDelegates(); }
static void TypeSafeDelegate(AsmHelper script, object instance) { FastInvokeDelegate sumInvoker = script.GetMethodInvoker("Claculator.Sum", 0, 0); //type unsafe delegate Action<int, int> Sum = delegate(int a, int b) { sumInvoker(instance, a, b); }; //type safe delegate Sum(1, 2); Sum(4, 7); }
static void TestMethodDelegates() { Assembly assembly = CSScript.LoadCode( @"using System; public class Calculator { static public void PrintSum(int a, int b) { Console.WriteLine(a + b); } public int Multiply(int a, int b) { return (a * b); } }"); AsmHelper calc = new AsmHelper(assembly); //using static method delegate var PrintSum = calc.GetStaticMethod("Calculator.PrintSum", 0, 0); PrintSum(1, 2); //using instance method delegate var obj = calc.CreateObject("Calculator"); var Multiply = calc.GetMethod(obj, "Multiply", 0, 0); Console.WriteLine(Multiply(3, 5)); //using general method delegate; can invoke both static and instance methods var methodInvoker = calc.GetMethodInvoker("Calculator.PrintSum", 0, 0); methodInvoker(null, 5, 12); }
static void TypeUnSafeDelegate(AsmHelper script, object instance) { FastInvokeDelegate Sum = script.GetMethodInvoker("Claculator.Sum", 0, 0); //streakly speaking the following calls are typre safe but they are not subject of //arguments checking Sum(instance, 1, 2); Sum(instance, 4, 7); //incorrect number of arguments //Sum(instance, 4, 7, 9); //runtime - OK, compiletime - OK //Sum(instance, 4); //runtime - Error, compiletime - OK }