Skip to main content

static_hook_basic/
static_hook_basic.rs

1//! EN: `StaticHook<T>` - the simplest typed inline hook pattern.
2//! CN: `StaticHook<T>` - 最简单、最常用的带类型 inline hook 写法。
3
4mod common;
5
6use dobby_rs_framework::prelude::*;
7
8// EN: A global hook handle is convenient for examples and small tools.
9// CN: 全局 hook 句柄适合示例/小工具使用。
10static HOOK: StaticHook<fn(i32) -> i32> = StaticHook::new();
11
12#[inline(never)]
13fn detour_add(x: i32) -> i32 {
14    // EN: Optional: run user callbacks.
15    // CN: 可选:执行用户的 before/after 回调。
16    HOOK.call_before();
17
18    // EN: Call the original implementation with modified arguments.
19    // CN: 修改参数后调用原函数。
20    let out = (HOOK.original())(x + 100);
21
22    HOOK.call_after();
23
24    // EN: Post-process return value.
25    // CN: 对返回值做二次处理。
26    out + 10
27}
28
29fn main() -> dobby_rs_framework::Result<()> {
30    common::init_example_logging();
31
32    // EN: Set optional callbacks (not required).
33    // CN: 设置可选回调(非必须)。
34    HOOK.set_before(|| log::info!("before"));
35    HOOK.set_after(|| log::info!("after"));
36
37    unsafe {
38        HOOK.install(
39            common::target_add as fn(i32) -> i32,
40            detour_add as fn(i32) -> i32,
41        )?;
42    }
43
44    let v = common::target_add(1);
45    println!("target_add(1) = {v}");
46
47    unsafe {
48        HOOK.uninstall()?;
49    }
50    Ok(())
51}