lokinet/llarp/win32/dll.hpp
Jason Rhinelander 9921dd6c77
Simplify dll loading via static function pointers
- Replaces RAII handling of DLLs with global function pointers.  (We
  don't unload the dll this way, but that seems unnecessary anyway).
- Simplifies code by just needing to call an init function, but not
  needing to pass around an object holding the function pointers.
- Adds a templated dll loader that takes the dll and a list of
  name/pointer pairs to load the dll and set the pointers in one shot.
2022-09-19 20:26:36 -03:00

35 lines
1.0 KiB
C++

#pragma once
#include <windows.h>
#include "exception.hpp"
#include <llarp/util/str.hpp>
namespace llarp::win32
{
namespace detail
{
HMODULE
load_dll(const std::string& dll);
template <typename Func, typename... More>
void
load_funcs(HMODULE handle, const std::string& name, Func*& f, More&&... more)
{
if (auto ptr = GetProcAddress(handle, name.c_str()))
f = reinterpret_cast<Func*>(ptr);
else
throw win32::error{fmt::format("function '{}' not found", name)};
if constexpr (sizeof...(More) > 0)
load_funcs(handle, std::forward<More>(more)...);
}
} // namespace detail
// Loads a DLL and extracts function pointers from it. Takes the dll name and pairs of
// name/function pointer arguments. Throws on failure.
template <typename Func, typename... More>
void
load_dll_functions(const std::string& dll, const std::string& fname, Func*& f, More&&... funcs)
{
detail::load_funcs(detail::load_dll(dll), fname, f, std::forward<More>(funcs)...);
}
} // namespace llarp::win32