Skip to content

Instantly share code, notes, and snippets.

@CleanCoder
Created September 7, 2018 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CleanCoder/baac40ae6cc1f6e33cb4db46b202a6b3 to your computer and use it in GitHub Desktop.
Save CleanCoder/baac40ae6cc1f6e33cb4db46b202a6b3 to your computer and use it in GitHub Desktop.
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