Skip to content

Instantly share code, notes, and snippets.

@guneysus
Forked from CleanCoder/Reflaction
Last active April 8, 2020 09:44
Show Gist options
  • Save guneysus/c38ce5dfc4c5302bd72d6922b2543fe2 to your computer and use it in GitHub Desktop.
Save guneysus/c38ce5dfc4c5302bd72d6922b2543fe2 to your computer and use it in GitHub Desktop.
FastMethodInvoker
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