- Home
- Developer Documentation
- Events and hooks
Events and hooks
React to game functions, constructors and game events.
A hook runs your callback when the game enters a function. The callback runs before the original code continues:
void cb(void* self, void* user); // self = first argument (for a method: this)Ways to install a hook#
| Call | Hooks |
|---|---|
rt.hook_api("server.getTime", cb, user, err) | A Lua API handler by name from the mapping |
rt.hook_ctor("c_scene_ropes", cb, user, err) | The constructors of a class |
rt.hook_method("class", slot, cb, user, err) | A virtual method by vtable slot |
rt.hook_rva(rva, cb, user, err) | A known address (relative to the image base) |
rt is sw::mod::rt(). Each call returns a sw::HookStatus.
Example#
#include "sw/mod.hpp"
#include <atomic>
SW_MOD("counter")
static std::atomic<int> g_calls{0};
static void on_call(void*, void*) { ++g_calls; }
void sw_mod_start() {
std::string err;
auto status = sw::mod::rt().hook_api("server.getTime", on_call, nullptr, err);
if (status != sw::HookStatus::ok) {
sw::mod::log("hook failed: %s (%s)", sw::to_string(status), err.c_str());
return;
}
while (sw::mod::sleep(5000)) sw::mod::log("calls: %d", g_calls.load());
}
void sw_mod_stop() {}Status values#
| Status | Meaning |
|---|---|
ok | The hook is installed. |
unsupported_arch | Not x64. |
target_invalid | The target is not inside the main module. |
already_hooked | A hook is already at this place. |
decode_failed | The first instructions cannot be decoded safely. |
relocation_failed | A short jump or no memory in reach. |
alloc_failed, write_failed | Memory could not be allocated or written. |
Limits#
sw::Hook::install_replace can skip the original function. Hooks are removed automatically when your mod unloads; remove one early with unhook.
Game events by name (for example the tile events) are in sw/events.hpp and sw/tiles.hpp.