CodeCompass
96 строк · 1.8 Кб
1#include <util/dynamiclibrary.h>
2
3namespace cc
4{
5namespace util
6{
7
8std::string DynamicLibrary::extension()
9{
10#ifdef WIN32
11return ".dll";
12#else
13return ".so";
14#endif
15}
16
17DynamicLibrary::DynamicLibrary(void* handle_) : _handle(handle_){}
18
19DynamicLibrary::DynamicLibrary(const std::string& path_)
20{
21if (path_.empty())
22{
23throw std::runtime_error("Empty path for dynamic library");
24}
25
26_handle = 0;
27
28#ifdef WIN32
29_handle = ::LoadLibraryA(name.c_str());
30if (!_handle)
31{
32DWORD errorCode = ::GetLastError();
33std::stringstream ss;
34ss << std::string("LoadLibrary(") << path_
35<< std::string(") Failed. errorCode: ")
36<< errorCode;
37throw std::runtime_error(ss.str());
38}
39#else
40_handle = ::dlopen(path_.c_str(), RTLD_NOW);
41if (!_handle)
42{
43const char *dlError = ::dlerror();
44std::string error = "Failed to load \"" + path_ + "\": ";
45error += (dlError) ? dlError : "";
46throw std::runtime_error(error);
47}
48#endif
49}
50
51DynamicLibrary::~DynamicLibrary()
52{
53if (_handle)
54{
55#ifdef WIN32
56::FreeLibrary((HMODULE)handle_);
57#else
58::dlclose(_handle);
59#endif
60}
61}
62
63void* DynamicLibrary::getSymbol(const std::string& name_) const
64{
65if (!_handle)
66throw std::runtime_error("Dynamic library handler is null!");
67
68#ifdef WIN32
69void *ret = ::GetProcAddress((HMODULE)handle_, symbol.c_str());
70if (ret == NULL)
71{
72DWORD errorCode = ::GetLastError();
73std::stringstream ss;
74ss << std::string("getSymbol(") << name_
75<< std::string(") Failed. errorCode: ")
76<< errorCode;
77throw std::runtime_error(ss.str());
78}
79#else
80void *ret = ::dlsym(_handle, name_.c_str());
81
82if (!ret)
83{
84const char *dlError = ::dlerror();
85std::string error = "Failed to retrieve symbol \"" + name_ + "\": ";
86error += (dlError) ? dlError : "";
87
88throw std::runtime_error(error);
89}
90
91#endif
92return ret;
93}
94
95} // util
96} // cc
97