|
16 | 16 | #include <qdmi/device.h> |
17 | 17 | #include <spdlog/spdlog.h> |
18 | 18 |
|
| 19 | +#include <array> |
19 | 20 | #include <cassert> |
20 | 21 | #include <cstddef> |
21 | 22 | #include <cstring> |
|
31 | 32 |
|
32 | 33 | #ifdef _WIN32 |
33 | 34 | #include <windows.h> |
| 35 | + |
| 36 | +#include <filesystem> |
34 | 37 | #else |
35 | 38 | #include <dlfcn.h> |
36 | 39 | #endif // _WIN32 |
37 | 40 |
|
38 | 41 | namespace qdmi { |
39 | 42 | #ifdef _WIN32 |
40 | | -#define DL_OPEN(lib) LoadLibraryA((lib)) |
| 43 | +namespace { |
| 44 | +/// Returns the directory of the currently loaded driver library. |
| 45 | +[[nodiscard]] auto getDriverDirectory() -> std::filesystem::path { |
| 46 | + HMODULE module = nullptr; |
| 47 | + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | |
| 48 | + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, |
| 49 | + reinterpret_cast<LPCWSTR>(&getDriverDirectory), |
| 50 | + &module) == 0) { |
| 51 | + return {}; |
| 52 | + } |
| 53 | + |
| 54 | + std::wstring buffer(MAX_PATH, L'\0'); |
| 55 | + DWORD size = 0; |
| 56 | + while (true) { |
| 57 | + size = GetModuleFileNameW(module, buffer.data(), |
| 58 | + static_cast<DWORD>(buffer.size())); |
| 59 | + if (size == 0) { |
| 60 | + return {}; |
| 61 | + } |
| 62 | + if (size < buffer.size()) { |
| 63 | + buffer.resize(size); |
| 64 | + break; |
| 65 | + } |
| 66 | + buffer.resize(buffer.size() * 2); |
| 67 | + } |
| 68 | + |
| 69 | + return std::filesystem::path(buffer).parent_path(); |
| 70 | +} |
| 71 | + |
| 72 | +/// Loads the device library with the given name, searching in the driver |
| 73 | +/// directory if no path is specified. |
| 74 | +[[nodiscard]] auto loadDeviceLibrary(const std::string& libName) -> HMODULE { |
| 75 | + const auto requested = std::filesystem::path(libName); |
| 76 | + |
| 77 | + const std::filesystem::path path = requested.has_parent_path() |
| 78 | + ? requested |
| 79 | + : getDriverDirectory() / requested; |
| 80 | + |
| 81 | + return LoadLibraryExW(path.wstring().c_str(), nullptr, |
| 82 | + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | |
| 83 | + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); |
| 84 | +} |
| 85 | +} // namespace |
| 86 | + |
| 87 | +#define DL_OPEN(lib) loadDeviceLibrary((lib)) |
41 | 88 | #define DL_SYM(lib, sym) \ |
42 | 89 | reinterpret_cast<void*>(GetProcAddress(static_cast<HMODULE>((lib)), (sym))) |
43 | 90 | #define DL_CLOSE(lib) FreeLibrary(static_cast<HMODULE>((lib))) |
|
0 commit comments