2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file library_loader.h Functions/types related to loading libraries dynamically. */
10 #ifndef LIBRARY_LOADER_H
11 #define LIBRARY_LOADER_H
16 * A function loaded from a library.
18 * Will automatically cast to the correct function pointer type on retrieval.
22 explicit Function(void *p
) : p(p
) {}
24 template <typename T
, typename
= std::enable_if_t
<std::is_function_v
<T
>>>
27 return reinterpret_cast<T
*>(this->p
);
35 * Load a library with the given filename.
37 explicit LibraryLoader(const std::string
&filename
)
39 this->handle
= this->OpenLibrary(filename
);
47 if (this->handle
!= nullptr) {
53 * Check whether an error occurred while loading the library or a function.
55 * @return Whether an error occurred.
59 return this->error
.has_value();
63 * Get the last error that occurred while loading the library or a function.
65 * @return The error message.
67 std::string
GetLastError()
69 return this->error
.value_or("No error");
73 * Get a function from a loaded library.
75 * @param symbol_name The name of the function to get.
76 * @return The function. Check HasError() before using.
78 Function
GetFunction(const std::string
&symbol_name
)
80 if (this->error
.has_value()) return Function(nullptr);
81 return Function(this->GetSymbol(symbol_name
));
86 * Open the library with the given filename.
88 * Should set error if any error occurred.
90 * @param filename The filename of the library to open.
92 void *OpenLibrary(const std::string
&filename
);
100 * Get a symbol from the library.
102 * Should set error if any error occurred.
104 * @param symbol_name The name of the symbol to get.
106 void *GetSymbol(const std::string
&symbol_name
);
108 std::optional
<std::string
> error
= {}; ///< The last error that occurred, if set.
109 void *handle
= nullptr; ///< Handle to the library.
112 #endif /* LIBRARY_LOADER_H */