util/library.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | /// @file library.cpp | ||
| 3 | /// @brief Opening shared libraries with dlopen, or LoadLibrary on Windows. | ||
| 4 | #include "ernie/util/library.h" | ||
| 5 | |||
| 6 | #if defined(_WIN32) | ||
| 7 | #include <windows.h> | ||
| 8 | #else | ||
| 9 | #include <dlfcn.h> | ||
| 10 | #endif | ||
| 11 | |||
| 12 | namespace ernie { | ||
| 13 | |||
| 14 | 6 | bool SharedLibrary::Open(std::initializer_list<const char*> names) { | |
| 15 | 24 | for (const char* name : names) { | |
| 16 | #if defined(_WIN32) | ||
| 17 | handle_ = reinterpret_cast<void*>(LoadLibraryA(name)); | ||
| 18 | #else | ||
| 19 | 18 | handle_ = dlopen(name, RTLD_NOW | RTLD_LOCAL); | |
| 20 | #endif | ||
| 21 | 18 | if (handle_ != nullptr) { | |
| 22 | return true; | ||
| 23 | } | ||
| 24 | } | ||
| 25 | return false; | ||
| 26 | } | ||
| 27 | |||
| 28 | 6 | SharedLibrary::~SharedLibrary() { | |
| 29 | 6 | if (handle_ != nullptr) { | |
| 30 | #if defined(_WIN32) | ||
| 31 | FreeLibrary(static_cast<HMODULE>(handle_)); | ||
| 32 | #else | ||
| 33 | ✗ | dlclose(handle_); | |
| 34 | #endif | ||
| 35 | } | ||
| 36 | 6 | } | |
| 37 | |||
| 38 | ✗ | void* SharedLibrary::Symbol(const char* name) const { | |
| 39 | #if defined(_WIN32) | ||
| 40 | return reinterpret_cast<void*>(GetProcAddress(static_cast<HMODULE>(handle_), name)); | ||
| 41 | #else | ||
| 42 | ✗ | return dlsym(handle_, name); | |
| 43 | #endif | ||
| 44 | } | ||
| 45 | |||
| 46 | } // namespace ernie | ||
| 47 |