Repository navigation
Expand file tree
/
Copy pathice_library.cpp
More file actions
112 lines (105 loc) · 2.56 KB
/
Copy pathice_library.cpp
File metadata and controls
112 lines (105 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* Ice multiplatform dynamic library loader.
*
* @copyright 2011 David Rebbe
*/
#include "ice_library.h"
#include "ice_exception.h"
#include <sstream>
using namespace ice;
Library::Library(std::string name)
{
m_name = name;
#if (defined(_WIN32) || defined(__WIN32__))
#ifdef UNICODE
int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, NULL, 0);
if (len)
{
wchar_t* n = new wchar_t[len];
MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, n, len);
m_lib = LoadLibrary(n);
delete[] n;
} else m_lib = NULL;
#else
m_lib = LoadLibrary(name.c_str());
#endif // UNICODE
if (m_lib == NULL)
{
DWORD error = GetLastError();
std::stringstream err;
err << "Failed to open library: '" << name <<
"' with error code: #" << error;
throw Exception(err.str());
}
#else
m_lib = dlopen(name.c_str(), RTLD_NOW);
if (m_lib == NULL)
{
std::stringstream err;
err << "Failed to open library '" << name <<
"': " << dlerror();
throw Exception(err.str());
}
#endif
}
Library::~Library()
{
if (this->isLoaded())
{
#if (defined(_WIN32) || defined(__WIN32__))
FreeLibrary(m_lib);
#else
dlclose(m_lib);
#endif
}
}
bool Library::isLoaded() const
{
return m_lib != NULL;
}
std::string Library::getPath(bool* okay)
{
if (okay)
*okay = false;
if (!isLoaded())
return m_name;
#if (defined(_WIN32) || defined(__WIN32__))
TCHAR buffer[MAX_PATH] = {0};
int len = GetModuleFileName(m_lib, buffer, MAX_PATH);
if (!len)
{
DWORD error = GetLastError();
std::stringstream err;
err << "Failed to get Library path: '" << m_name <<
"' with error code: #" << error;
throw Exception(err.str());
}
#ifdef UNICODE
int length = WideCharToMultiByte(CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL);
if (length)
{
char* temp = new char[MAX_PATH];
WideCharToMultiByte(CP_UTF8, 0, buffer, -1, temp, length, NULL, NULL);
std::stringstream ss;
ss << temp;
if (okay)
*okay = true;
return ss.str();
}
#else
std::stringstream ss;
ss << buffer;
if (okay)
*okay = true;
return ss.str();
#endif // UNICODE
#else
// Linux doesn't really have a way to get the library path from the handle and
// its recommended to use absolute paths when loading with dlopen().
#endif // WIN32
return m_name;
}
HMODULE const& Library::_library() const
{
return m_lib;
}