1 // license:GPL-2.0+
2 // copyright-holders:Couriersud
3
4 #include "pdynlib.h"
5
6 #ifdef _WIN32
7 #include "windows.h"
8 #else
9 #include <dlfcn.h>
10 #endif
11
12 #include <type_traits>
13
14 namespace plib
15 {
16 using winapi_string = std::conditional<compile_info::unicode::value,
17 pwstring, pu8string>::type;
18
dynlib(const pstring & libname)19 dynlib::dynlib(const pstring &libname)
20 : m_lib(nullptr)
21 {
22 #ifdef _WIN32
23 //fprintf(stderr, "win: loading <%s>\n", libname.c_str());
24 if (!libname.empty())
25 m_lib = LoadLibrary(winapi_string(putf8string(libname)).c_str());
26 else
27 m_lib = GetModuleHandle(nullptr);
28 #elif defined(__EMSCRIPTEN__)
29 //no-op
30 #else
31 //printf("loading <%s>\n", libname.c_str());
32 if (!libname.empty())
33 m_lib = dlopen(putf8string(libname).c_str(), RTLD_LAZY);
34 else
35 m_lib = dlopen(nullptr, RTLD_LAZY);
36 #endif
37 if (m_lib != nullptr)
38 set_loaded(true);
39 //else
40 // printf("library <%s> not found: %s\n", libname.c_str(), dlerror());
41 }
42
dynlib(const pstring & path,const pstring & libname)43 dynlib::dynlib(const pstring &path, const pstring &libname)
44 : m_lib(nullptr)
45 {
46 // FIXME: implement path search
47 plib::unused_var(path);
48 // printf("win: loading <%s>\n", libname.c_str());
49 #ifdef _WIN32
50 if (!libname.empty())
51 m_lib = LoadLibrary(winapi_string(putf8string(libname)).c_str());
52 else
53 m_lib = GetModuleHandle(nullptr);
54 #elif defined(__EMSCRIPTEN__)
55 //no-op
56 #else
57 //printf("loading <%s>\n", libname.c_str());
58 if (!libname.empty())
59 m_lib = dlopen(putf8string(libname).c_str(), RTLD_LAZY);
60 else
61 m_lib = dlopen(nullptr, RTLD_LAZY);
62 #endif
63 if (m_lib != nullptr)
64 set_loaded(true);
65 else
66 {
67 //printf("library <%s> not found!\n", libname.c_str());
68 }
69 }
70
~dynlib()71 dynlib::~dynlib()
72 {
73 if (m_lib != nullptr)
74 {
75 #ifdef _WIN32
76 #else
77 dlclose(m_lib);
78 //printf("Closed %s\n", dlerror());
79 #endif
80 }
81 }
82
getsym_p(const pstring & name) const83 void *dynlib::getsym_p(const pstring &name) const noexcept
84 {
85 #ifdef _WIN32
86 return (void *) GetProcAddress((HMODULE) m_lib, putf8string(name).c_str());
87 #else
88 return dlsym(m_lib, putf8string(name).c_str());
89 #endif
90 }
91
92 } // namespace plib
93