31 static constexpr size_t kMaxFunctionsNotFound = 10;
37 if (library_handle_ ==
nullptr) {
42 FreeLibrary(
static_cast<HINSTANCE
>(library_handle_));
43#elif defined(__GNUC__)
44 dlclose(library_handle_);
48 bool TryToLoad(
const std::string& library_name) {
49 library_name_ = std::string(library_name);
51 library_handle_ =
static_cast<void*
>(LoadLibraryA(library_name.c_str()));
52#elif defined(__GNUC__)
53 library_handle_ = dlopen(library_name.c_str(), RTLD_NOW);
55 return library_handle_ !=
nullptr;
58 bool LibraryIsLoaded()
const {
return library_handle_ !=
nullptr; }
60 const std::vector<std::string>& FunctionsNotFound()
const {
61 return functions_not_found_;
65 std::function<T> GetFunction(
const char* function_name) {
66 const void* function_address =
68 static_cast<void*
>(GetProcAddress(
69 static_cast<HINSTANCE
>(library_handle_), function_name));
71 dlsym(library_handle_, function_name);
75 if (!function_address &&
76 functions_not_found_.size() < kMaxFunctionsNotFound)
77 functions_not_found_.push_back(function_name);
79 return TypeParser<T>::CreateFunction(function_address);
83 std::function<T> GetFunction(
const std::string& function_name) {
84 return GetFunction<T>(function_name.c_str());
88 void GetFunction(std::function<T>* function,
const char* function_name) {
89 *function = GetFunction<T>(function_name);
93 void GetFunction(std::function<T>* function,
94 const std::string function_name) {
95 GetFunction<T>(function, function_name.c_str());
99 void* library_handle_ =
nullptr;
100 std::string library_name_;
101 std::vector<std::string> functions_not_found_;
103 template <
typename T>
104 struct TypeParser {};
106 template <
typename Ret,
typename... Args>
107 struct TypeParser<Ret(Args...)> {
108 static std::function<Ret(Args...)> CreateFunction(
109 const void* function_address) {
110 return std::function<Ret(Args...)>(
reinterpret_cast<Ret (*)(Args...)
>(
111 const_cast<void*
>(function_address)));