Created
September 7, 2018 08:04
-
-
Save CleanCoder/baac40ae6cc1f6e33cb4db46b202a6b3 to your computer and use it in GitHub Desktop.
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
1. A General Fast Method Invoker (https://www.codeproject.com/Articles/14593/A-General-Fast-Method-Invoker) | |
public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo) | |
{ | |
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, | |
typeof(object), new Type[] { typeof(object), | |
typeof(object[]) }, | |
methodInfo.DeclaringType.Module); | |
ILGenerator il = dynamicMethod.GetILGenerator(); | |
ParameterInfo[] ps = methodInfo.GetParameters(); | |
Type[] paramTypes = new Type[ps.Length]; | |
for (int i = 0; i < paramTypes.Length; i++) | |
{ | |
paramTypes[i] = ps[i].ParameterType; | |
} | |
LocalBuilder[] locals = new LocalBuilder[paramTypes.Length]; | |
for (int i = 0; i < paramTypes.Length; i++) | |
{ | |
locals[i] = il.DeclareLocal(paramTypes[i]); | |
} | |
for (int i = 0; i < paramTypes.Length; i++) | |
{ | |
il.Emit(OpCodes.Ldarg_1); | |
EmitFastInt(il, i); | |
il.Emit(OpCodes.Ldelem_Ref); | |
EmitCastToReference(il, paramTypes[i]); | |
il.Emit(OpCodes.Stloc, locals[i]); | |
} | |
il.Emit(OpCodes.Ldarg_0); | |
for (int i = 0; i < paramTypes.Length; i++) | |
{ | |
il.Emit(OpCodes.Ldloc, locals[i]); | |
} | |
il.EmitCall(OpCodes.Call, methodInfo, null); | |
if (methodInfo.ReturnType == typeof(void)) | |
il.Emit(OpCodes.Ldnull); | |
else | |
EmitBoxIfNeeded(il, methodInfo.ReturnType); | |
il.Emit(OpCodes.Ret); | |
FastInvokeHandler invoder = | |
(FastInvokeHandler)dynamicMethod.CreateDelegate( | |
typeof(FastInvokeHandler)); | |
return invoder; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment