Skip to content

Instantly share code, notes, and snippets.

@Sergio0694
Created September 21, 2019 00:01
Show Gist options
  • Save Sergio0694/5a463b83f245ac2b91c003c222a3b0a6 to your computer and use it in GitHub Desktop.
Save Sergio0694/5a463b83f245ac2b91c003c222a3b0a6 to your computer and use it in GitHub Desktop.
public static void EmitAddOffset(this ILGenerator il, int offset)
{
// Push the offset to the stack
if (offset <= 8)
{
il.Emit(offset switch
{
0 => OpCodes.Ldc_I4_0,
1 => OpCodes.Ldc_I4_1,
2 => OpCodes.Ldc_I4_2,
3 => OpCodes.Ldc_I4_3,
4 => OpCodes.Ldc_I4_4,
5 => OpCodes.Ldc_I4_5,
6 => OpCodes.Ldc_I4_6,
7 => OpCodes.Ldc_I4_7,
8 => OpCodes.Ldc_I4_8,
_ => throw new InvalidOperationException($"Invalid offset value [{offset}]")
});
}
else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset);
else il.Emit(OpCodes.Ldc_I4, offset);
il.Emit(OpCodes.Conv_I); // Convert the int to native int (void*)
il.Emit(OpCodes.Add); // Pop the two values, sum them and push the result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment