Memory Hook 示例
作用
這個示例用 pl::memory::resolveSignature() 解析目標,用
pl::memory::HookHandle 安裝 hook,並在 disable() 或句柄析構時釋放。
頭文件
C++
#include <pl/memory/Hook.hpp>
#include <pl/memory/Signature.hpp>示例
C++
#include <pl/Mod.hpp>
#include <pl/memory/Hook.hpp>
#include <pl/memory/Signature.hpp>
class MyMod {
public:
bool enable() {
const auto target = pl::memory::resolveSignature(
"Game_update", "libminecraftpe.so");
if (target == 0) {
getSelf().getLogger().warn("Game_update was not found");
return true;
}
mUpdateHook = pl::memory::HookHandle(
reinterpret_cast<void *>(target),
reinterpret_cast<void *>(&updateHook),
reinterpret_cast<void **>(&mOriginalUpdate));
return mUpdateHook.installed();
}
bool disable() {
mUpdateHook.reset();
return true;
}
[[nodiscard]] ll::mod::NativeMod &getSelf() const;
private:
using UpdateFn = void (*)(void *);
static void updateHook(void *self) {
instance().mOriginalUpdate(self);
}
static MyMod &instance();
UpdateFn mOriginalUpdate{};
pl::memory::HookHandle mUpdateHook;
};注意
- detour 簽名必須和目標函數完全一致。
- hook handle 應存放在模組自有狀態中,不要放在局部變量裡。
- 優先使用明確的生命週期清理,不要依賴 constructor-time 自動註冊。