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
项目或将其源码加入到你的解决方案。 -
按照以下示例使用:
using System.Runtime.CompilerServices;
using EleCho.SharpHook;
Hook.Initialize();
Hook.ReplaceMethod(
typeof(MyClass).GetConstructors().First(),
typeof(MyClassHook).GetMethod(nameof(MyClassHook.HookCtor))!,
typeof(MyClassHook).GetMethod(nameof(MyClassHook.OriginalCtor))!);
MyClass obj = new MyClass();
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 = new MyClass();
Console.WriteLine($"2 + 3 = {obj.Sum(2, 3)}");
public static class MyClassHook
{
public static int OriginalSum(MyClass @this, int a, int b) => throw null!;
public static int HookSum(MyClass @this, int a, int b) => OriginalSum(@this, a, b) + a * b;
public static int OriginalCtor(MyClass @this) => throw null!;
public static void HookCtor(MyClass @this) => Console.WriteLine("Hook Ctor");
}
public class MyClass
{
public MyClass() => Console.WriteLine("Original Ctor");
public int Sum(int a, int b) => 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。