CodeCompass

Форк
0
/
dynamiclibrary.cpp 
96 строк · 1.8 Кб
1
#include <util/dynamiclibrary.h>
2

3
namespace cc
4
{
5
namespace util
6
{
7

8
std::string DynamicLibrary::extension()
9
{
10
#ifdef WIN32
11
  return ".dll";
12
#else
13
  return ".so";
14
#endif
15
}
16

17
DynamicLibrary::DynamicLibrary(void* handle_) : _handle(handle_){}
18

19
DynamicLibrary::DynamicLibrary(const std::string& path_)
20
{
21
  if (path_.empty())
22
  {
23
    throw std::runtime_error("Empty path for dynamic library");
24
  }
25

26
  _handle = 0;
27

28
#ifdef WIN32
29
  _handle = ::LoadLibraryA(name.c_str());
30
  if (!_handle)
31
  {
32
    DWORD errorCode = ::GetLastError();
33
    std::stringstream ss;
34
    ss << std::string("LoadLibrary(") << path_
35
    << std::string(") Failed. errorCode: ")
36
    << errorCode;
37
    throw std::runtime_error(ss.str());
38
  }
39
#else
40
  _handle = ::dlopen(path_.c_str(), RTLD_NOW);
41
  if (!_handle)
42
  {
43
    const char *dlError = ::dlerror();
44
    std::string error = "Failed to load \"" + path_ + "\": ";
45
    error += (dlError) ? dlError : "";
46
    throw std::runtime_error(error);
47
  }
48
#endif
49
}
50

51
DynamicLibrary::~DynamicLibrary()
52
{
53
  if (_handle)
54
  {
55
#ifdef WIN32
56
    ::FreeLibrary((HMODULE)handle_);
57
#else
58
    ::dlclose(_handle);
59
#endif
60
  }
61
}
62

63
void* DynamicLibrary::getSymbol(const std::string& name_) const
64
{
65
  if (!_handle)
66
    throw std::runtime_error("Dynamic library handler is null!");
67

68
#ifdef WIN32
69
  void *ret = ::GetProcAddress((HMODULE)handle_, symbol.c_str());
70
  if (ret == NULL)
71
  {
72
    DWORD errorCode = ::GetLastError();
73
    std::stringstream ss;
74
    ss << std::string("getSymbol(") << name_
75
    << std::string(") Failed. errorCode: ")
76
    << errorCode;
77
    throw std::runtime_error(ss.str());
78
  }
79
#else
80
  void *ret = ::dlsym(_handle, name_.c_str());
81

82
  if (!ret)
83
  {
84
    const char *dlError = ::dlerror();
85
    std::string error = "Failed to retrieve symbol \"" + name_ + "\": ";
86
    error += (dlError) ? dlError : "";
87

88
    throw std::runtime_error(error);
89
  }
90

91
#endif
92
  return ret;
93
}
94

95
} // util
96
} // cc
97

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.