SafetyHook provides a high-level API for creating inline hooks. You can use safetyhook::create_inline to redirect a target function to a detour function. To call the original function from within the detour, use the .call<T>(...) method on the returned hook object.
Note: The target function should ideally be marked with __declspec(noinline) to ensure predictable hooking behavior.
#include <iostream>
#include <safetyhook.hpp>
__declspec(noinline) int add(int x, int y) {
return x + y;
}
SafetyHookInline g_add_hook{};
int hook_add(int x, int y) {
// Call the original function using the hook object
return g_add_hook.call<int>(x * 2, y * 2);
}
int main() {
std::cout << "unhooked add(2, 3) = " << add(2, 3) << "\n";
// Create a hook on add
g_add_hook = safetyhook::create_inline(reinterpret_cast<void*>(add), reinterpret_cast<void*>(hook_add));
std::cout << "hooked add(3, 4) = " << add(3, 4) << "\n";
// Remove the hook by resetting the object
g_add_hook = {};
std::cout << "unhooked add(5, 6) = " << add(5, 6) << "\n";
return 0;
}