EleCho.SharpHook 是一个 .NET 动态方法替换库,允许你在运行时替换和恢复类的方法实现,无需重新编译原始代码。
- 支持运行时替换构造函数和普通方法。
- 保留原始方法调用能力,便于链式调用或扩展原有逻辑。
- 提供易用 API:
Hook.ReplaceMethod、Hook.RestoreMethod等。 - 支持还原被替换的方法。
- 无需原始类源码,仅需反射信息即可替换。
- 兼容主流 .NET 运行环境。
- 仅支持 Windows x86 和 x64 平台。
- 不支持 NativeAOT。
- 项目依赖:
- Microsoft.Diagnostics.Runtime:用于获取方法的本机代码地址。
- MinHook:用于底层 native hook。
克隆本仓库:
git clone https://github.com/OrgEleCho/EleCho.SharpHook.git
在你的项目中直接引用
EleCho.SharpHook项目或将其源码加入到你的解决方案。按照以下示例使用:
usingSystem.Runtime.CompilerServices;usingEleCho.SharpHook;Hook.Initialize();Hook.ReplaceMethod(typeof(MyClass).GetConstructors().First(),typeof(MyClassHook).GetMethod(nameof(MyClassHook.HookCtor))!,typeof(MyClassHook).GetMethod(nameof(MyClassHook.OriginalCtor))!);MyClassobj=newMyClass();Console.WriteLine($"2 + 3 = {obj.Sum(2,3)}");Hook.ReplaceMethod(typeof(MyClass).GetMethod(nameof(MyClass.Sum))!,typeof(MyClassHook).GetMethod(nameof(MyClassHook.HookSum))!,typeof(MyClassHook).GetMethod(nameof(MyClassHook.OriginalSum))!);Console.WriteLine($"2 + 3 = {obj.Sum(2,3)}");Hook.RestoreMethod(typeof(MyClass).GetConstructors().First());Hook.RestoreMethod(typeof(MyClass).GetMethod(nameof(MyClass.Sum))!);obj=newMyClass();Console.WriteLine($"2 + 3 = {obj.Sum(2,3)}");publicstaticclassMyClassHook{publicstaticintOriginalSum(MyClass@this,inta,intb)=>thrownull!;publicstaticintHookSum(MyClass@this,inta,intb)=>OriginalSum(@this,a,b)+a*b;publicstaticintOriginalCtor(MyClass@this)=>thrownull!;publicstaticvoidHookCtor(MyClass@this)=>Console.WriteLine("Hook Ctor");}publicclassMyClass{publicMyClass()=>Console.WriteLine("Original Ctor");publicintSum(inta,intb)=>a+b;}输出示例:
Hook Ctor
2 + 3 = 5
2 + 3 = 11
Original Ctor
2 + 3 = 5
Hook.Initialize():初始化 Hook,程序启动时调用。Hook.ReplaceMethod(MethodBase targetMethod, MethodInfo hookMethod, MethodInfo originalMethod):将 target 方法替换为 replacement,并通过 original 保存原始实现代理。Hook.RestoreMethod(MethodBase targetMethod):恢复被替换的方法为原始实现。
- 仅支持 Windows x86/x64,暂不支持其他平台和 NativeAOT。
- 替换的方法签名必须完全一致,包括参数类型和顺序。
- 原始方法代理(如
OriginalSum)实现需抛出异常(如throw null!),库会自动注入原始实现。 - 可能需要管理员权限或特殊运行环境,具体依赖于 .NET 运行时版本和底层 hook 机制。
欢迎提交 Issue 或 PR,或者通过 Discussions 交流使用经验和建议!
本项目采用 MIT 许可证。详情请见 LICENSE。