Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Harmony;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace ConsoleApp44
- {
- class Program
- {
- static void Main(string[] args)
- {
- HarmonyInstance instance = HarmonyInstance.Create("test");
-
- Type self = typeof(Program);
- var targetMethod = self.GetMethod(nameof(Target));
- MethodInfo patchMethod = ResolveDynamicPatch(self);
- instance.Patch(targetMethod, new HarmonyMethod(patchMethod));
-
- Target();
- Console.ReadLine();
- }
-
- private static MethodInfo ResolveStaticPatch(Type self)
- {
- var patchMethod = self.GetMethod(nameof(Prefix));
- return patchMethod;
- }
- private static MethodInfo ResolveDynamicPatch(Type self)
- {
- MethodInfo consoleWriteLine = typeof(Console).GetMethod("WriteLine", new Type[] {typeof(String)});
-
- Type returnType = typeof(void);
- Type[] parameterTypes = new Type[0];
- DynamicMethod dynamicMethod = new DynamicMethod("MyMethod", returnType, parameterTypes);
-
- var il = dynamicMethod.GetILGenerator();
- il.Emit(OpCodes.Ldstr, "hello world");
- il.EmitCall(OpCodes.Call, consoleWriteLine, null);
- il.Emit(OpCodes.Ret);
-
- DelegateTypeFactory factory = new DelegateTypeFactory();
- Type delegateType = factory.CreateDelegateType(dynamicMethod);
-
- var method = delegateType.GetMethod("Invoke") ?? throw new ArgumentException();
- return method;
- }
-
- public static void Target()
- {
-
- }
-
- public static void Prefix()
- {
- Console.WriteLine("hello");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement