From 4ad739ec63c9a11f0537a884ae2a4c56d6bab10b Mon Sep 17 00:00:00 2001 From: Vaxry Date: Sat, 20 Apr 2024 20:16:42 +0100 Subject: HookSystem: improve callback safety --- src/managers/HookSystemManager.hpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'src/managers/HookSystemManager.hpp') diff --git a/src/managers/HookSystemManager.hpp b/src/managers/HookSystemManager.hpp index ca8e9006..4b27fadf 100644 --- a/src/managers/HookSystemManager.hpp +++ b/src/managers/HookSystemManager.hpp @@ -16,8 +16,8 @@ typedef std::function HOOK_CALLBACK_FN; struct SCallbackFNPtr { - HOOK_CALLBACK_FN* fn = nullptr; - HANDLE handle = nullptr; + std::weak_ptr fn; + HANDLE handle = nullptr; }; #define EMIT_HOOK_EVENT(name, param) \ @@ -40,21 +40,21 @@ class CHookSystemManager { public: CHookSystemManager(); - // returns the pointer to the function - HOOK_CALLBACK_FN* hookDynamic(const std::string& event, HOOK_CALLBACK_FN fn, HANDLE handle = nullptr); - void hookStatic(const std::string& event, HOOK_CALLBACK_FN* fn, HANDLE handle = nullptr); - void unhook(HOOK_CALLBACK_FN* fn); + // returns the pointer to the function. + // losing this pointer (letting it get destroyed) + // will equal to unregistering the callback. + [[nodiscard("Losing this pointer instantly unregisters the callback")]] std::shared_ptr hookDynamic(const std::string& event, HOOK_CALLBACK_FN fn, + HANDLE handle = nullptr); + void unhook(std::shared_ptr fn); - void emit(const std::vector* callbacks, SCallbackInfo& info, std::any data = 0); + void emit(std::vector* const callbacks, SCallbackInfo& info, std::any data = 0); std::vector* getVecForEvent(const std::string& event); bool m_bCurrentEventPlugin = false; jmp_buf m_jbHookFaultJumpBuf; private: - // todo: this is slow. Maybe static ptrs should be somehow allowed. unique ptr for vec? - std::list>> m_lpRegisteredHooks; - std::list m_lCallbackFunctions; + std::unordered_map> m_mRegisteredHooks; }; inline std::unique_ptr g_pHookSystem; \ No newline at end of file -- cgit v1.2.3