alpaqa pi-pico
Nonconvex constrained optimization
Loading...
Searching...
No Matches
dl.cpp
Go to the documentation of this file.
1#include <alpaqa/util/dl.hpp>
2
3#if _WIN32
4#include <windows.h>
5#else
6#include <dlfcn.h>
7#endif
8
9#include <cassert>
10
11namespace alpaqa::util {
12
13#if _WIN32
14std::shared_ptr<char> get_last_error_msg() {
15 char *err = nullptr;
20 reinterpret_cast<char *>(&err), 0, NULL) != 0) {
21 return std::shared_ptr<char>{err, [](char *e) { LocalFree(e); }};
22 } else {
23 static char msg[] = "(failed to get error message)";
24 return std::shared_ptr<char>{msg, [](char *) {}};
25 }
26}
27
28std::shared_ptr<void> load_lib(const std::filesystem::path &so_filename,
29 [[maybe_unused]] DynamicLoadFlags flags) {
30 assert(!so_filename.empty());
31 void *h = LoadLibraryW(so_filename.c_str());
32 if (!h)
33 throw dynamic_load_error("Unable to load \"" + so_filename.string() +
34 "\": " + get_last_error_msg().get());
35#if ALPAQA_NO_DLCLOSE
36 return std::shared_ptr<void>{h, +[](void *) {}};
37#else
38 return std::shared_ptr<void>{
39 h, +[](void *h) { FreeLibrary(static_cast<HMODULE>(h)); }};
40#endif
41}
42
43void *load_func(void *handle, const std::string &name) {
44 assert(handle);
45 auto *h = GetProcAddress(static_cast<HMODULE>(handle), name.c_str());
46 if (!h)
47 throw dynamic_load_error("Unable to load function '" + name +
48 "': " + get_last_error_msg().get());
49 return reinterpret_cast<void *>(h);
50}
51#else
52std::shared_ptr<void> load_lib(const std::filesystem::path &so_filename,
53 DynamicLoadFlags dl_flags) {
54 assert(!so_filename.empty());
55 ::dlerror();
56 void *h = ::dlopen(so_filename.c_str(), dl_flags);
57 if (auto *err = ::dlerror())
59#if ALPAQA_NO_DLCLOSE
60 return std::shared_ptr<void>{h, +[](void *) {}};
61#else
62 return std::shared_ptr<void>{h, &::dlclose};
63#endif
64}
65
66void *load_func(void *handle, const std::string &name) {
67 assert(handle);
68 ::dlerror();
69 auto *h = ::dlsym(handle, name.c_str());
70 if (auto *err = ::dlerror())
71 throw dynamic_load_error("Unable to load function '" + name +
72 "': " + err);
73 return h;
74}
75#endif
76
77} // namespace alpaqa::util
void * load_func(void *lib_handle, const std::string &name)
Get a pointer to a function inside of a loaded DLL or SO file.
Definition dl.cpp:66
std::shared_ptr< void > load_lib(const std::filesystem::path &so_filename, DynamicLoadFlags flags)
Load a DLL or SO file.
Definition dl.cpp:52
constexpr const auto inf
Definition config.hpp:112
Flags to be passed to dlopen.
Definition dl-flags.hpp:8
Failed to load a DLL or SO file, or failed to access a function in it.
Definition dl.hpp:12