Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. using Harmony;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Reflection.Emit;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace ConsoleApp44
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. HarmonyInstance instance = HarmonyInstance.Create("test");
  16. Type self = typeof(Program);
  17. var targetMethod = self.GetMethod(nameof(Target));
  18. MethodInfo patchMethod = ResolveDynamicPatch(self);
  19. instance.Patch(targetMethod, new HarmonyMethod(patchMethod));
  20. Target();
  21. Console.ReadLine();
  22. }
  23. private static MethodInfo ResolveStaticPatch(Type self)
  24. {
  25. var patchMethod = self.GetMethod(nameof(Prefix));
  26. return patchMethod;
  27. }
  28.  
  29. private static MethodInfo ResolveDynamicPatch(Type self)
  30. {
  31. MethodInfo consoleWriteLine = typeof(Console).GetMethod("WriteLine", new Type[] {typeof(String)});
  32. Type returnType = typeof(void);
  33. Type[] parameterTypes = new Type[0];
  34. DynamicMethod dynamicMethod = new DynamicMethod("MyMethod", returnType, parameterTypes);
  35. var il = dynamicMethod.GetILGenerator();
  36. il.Emit(OpCodes.Ldstr, "hello world");
  37. il.EmitCall(OpCodes.Call, consoleWriteLine, null);
  38. il.Emit(OpCodes.Ret);
  39. DelegateTypeFactory factory = new DelegateTypeFactory();
  40. Type delegateType = factory.CreateDelegateType(dynamicMethod);
  41. var method = delegateType.GetMethod("Invoke") ?? throw new ArgumentException();
  42. return method;
  43. }
  44. public static void Target()
  45. {
  46. }
  47. public static void Prefix()
  48. {
  49. Console.WriteLine("hello");
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement