util/library.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | /// @file library.h | ||
| 3 | /// @brief Shared libraries opened at run time, for optional drivers such as CUDA's that Ernie | ||
| 4 | /// neither links nor requires. | ||
| 5 | #pragma once | ||
| 6 | |||
| 7 | #include <initializer_list> | ||
| 8 | |||
| 9 | namespace ernie { | ||
| 10 | |||
| 11 | /// @brief An opened shared library, closed when destroyed. | ||
| 12 | class SharedLibrary { | ||
| 13 | public: | ||
| 14 | /// @brief Opens the first of `names` that loads. | ||
| 15 | /// @return Whether one did. | ||
| 16 | bool Open(std::initializer_list<const char*> names); | ||
| 17 | ~SharedLibrary(); | ||
| 18 | SharedLibrary() = default; | ||
| 19 | SharedLibrary(const SharedLibrary&) = delete; | ||
| 20 | SharedLibrary& operator=(const SharedLibrary&) = delete; | ||
| 21 | |||
| 22 | explicit operator bool() const { | ||
| 23 | return handle_ != nullptr; | ||
| 24 | } | ||
| 25 | /// @return The address of `name`, or null when the library has none. | ||
| 26 | void* Symbol(const char* name) const; | ||
| 27 | /// @brief Looks up `name` as a function pointer of type `F`. | ||
| 28 | /// @return Whether it was found. | ||
| 29 | ✗ | template <typename F> bool Load(F& function, const char* name) const { | |
| 30 | ✗ | function = reinterpret_cast<F>(Symbol(name)); | |
| 31 | return function != nullptr; | ||
| 32 | } | ||
| 33 | |||
| 34 | private: | ||
| 35 | void* handle_ = nullptr; | ||
| 36 | }; | ||
| 37 | |||
| 38 | } // namespace ernie | ||
| 39 |