GSLAM  3.0.0
SharedLibrary.h
1 // GSLAM - A general SLAM framework and benchmark
2 // Copyright 2018 PILAB Inc. All rights reserved.
3 // https://github.com/zdzhaoyong/GSLAM
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are met:
7 //
8 // * Redistributions of source code must retain the above copyright notice,
9 // this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright notice,
11 // this list of conditions and the following disclaimer in the documentation
12 // and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors may be
14 // used to endorse or promote products derived from this software without
15 // specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 // POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: zd5945@126.com (Yong Zhao)
30 //
31 // SharedLibrary is used to load a shared library in different systems
32 
33 #ifndef GSLAM_SHAREDLIBRARY_H
34 #define GSLAM_SHAREDLIBRARY_H
35 
36 #include <iostream>
37 #include <set>
38 
39 #if (defined(_WIN32) || defined(_WIN64)) && !defined(__CYGWIN__)// Windows
40 
41 #include <windows.h>
42 #include <io.h>
43 // A list of annoying macros to #undef.
44 // Feel free to extend as required.
45 #undef GetBinaryType
46 #undef GetShortPathName
47 #undef GetLongPathName
48 #undef GetEnvironmentStrings
49 #undef SetEnvironmentStrings
50 #undef FreeEnvironmentStrings
51 #undef FormatMessage
52 #undef EncryptFile
53 #undef DecryptFile
54 #undef CreateMutex
55 #undef OpenMutex
56 #undef CreateEvent
57 #undef OpenEvent
58 #undef CreateSemaphore
59 #undef OpenSemaphore
60 #undef LoadLibrary
61 #undef GetModuleFileName
62 #undef CreateProcess
63 #undef GetCommandLine
64 #undef GetEnvironmentVariable
65 #undef SetEnvironmentVariable
66 #undef ExpandEnvironmentStrings
67 #undef OutputDebugString
68 #undef FindResource
69 #undef UpdateResource
70 #undef FindAtom
71 #undef AddAtom
72 #undef GetSystemDirector
73 #undef GetTempPath
74 #undef GetTempFileName
75 #undef SetCurrentDirectory
76 #undef GetCurrentDirectory
77 #undef CreateDirectory
78 #undef RemoveDirectory
79 #undef CreateFile
80 #undef DeleteFile
81 #undef SearchPath
82 #undef CopyFile
83 #undef MoveFile
84 #undef ReplaceFile
85 #undef GetComputerName
86 #undef SetComputerName
87 #undef GetUserName
88 #undef LogonUser
89 #undef GetVersion
90 #undef GetObject
91 
92 #else // Linux
93 
94 #include <unistd.h>
95 #include <dlfcn.h>
96 
97 // Note: cygwin is missing RTLD_LOCAL, set it to 0
98 #if defined(__CYGWIN__) && !defined(RTLD_LOCAL)
99 #define RTLD_LOCAL 0
100 #endif
101 
102 #endif
103 
104 #include "Glog.h"
105 
106 
107 namespace GSLAM {
108 
110  /// The SharedLibrary class dynamically
111  /// loads shared libraries at run-time.
112 {
113  enum Flags
114  {
115  SHLIB_GLOBAL_IMPL = 1,
116  SHLIB_LOCAL_IMPL = 2
117  };
118 public:
119  typedef std::mutex MutexRW;
120  typedef std::unique_lock<std::mutex> WriteMutex;
121  SharedLibrary():_handle(NULL){}
122  /// Creates a SharedLibrary object.
123 
124  SharedLibrary(const std::string& path):_handle(NULL)
125  {
126  load(path);
127  }
128  /// Creates a SharedLibrary object and loads a library
129  /// from the given path.
130 
131  virtual ~SharedLibrary(){
132  if(isLoaded())
133  {
134 #ifndef NDEBUG
135 // std::cerr<<"SharedLibrary "<<_path<<" released."<<std::endl;
136 #endif
137  }
138  }
139  /// Destroys the SharedLibrary. The actual library
140  /// remains loaded.
141 
142  bool load(const std::string& path,int flags=0)
143  {
144 
145  WriteMutex lock(_mutex);
146 
147  if (_handle)
148  return false;
149 
150 #if (defined(_WIN32) || defined(_WIN64)) && !defined(__CYGWIN__)// Windows
151 
152  flags |= LOAD_WITH_ALTERED_SEARCH_PATH;
153  _handle = LoadLibraryExA(path.c_str(), 0, flags);
154  if (!_handle) return false;
155 #else
156  int realFlags = RTLD_LAZY;
157  if (flags & SHLIB_LOCAL_IMPL)
158  realFlags |= RTLD_LOCAL;
159  else
160  realFlags |= RTLD_GLOBAL;
161  _handle = dlopen(path.c_str(), realFlags);
162  if (!_handle)
163  {
164  const char* err = dlerror();
165  std::cerr<<"Can't open file "<<path<<" since "<<err<<std::endl;
166  return false;
167  }
168 
169 #endif
170  _path = path;
171  return true;
172  }
173  /// Loads a shared library from the given path.
174  /// Throws a LibraryAlreadyLoadedException if
175  /// a library has already been loaded.
176  /// Throws a LibraryLoadException if the library
177  /// cannot be loaded.
178 
179  void unload()
180  {
181  WriteMutex lock(_mutex);
182 
183  if (_handle)
184  {
185 #if (defined(_WIN32) || defined(_WIN64)) && !defined(__CYGWIN__)// Windows
186  FreeLibrary((HMODULE) _handle);
187 #else
188  dlclose(_handle);
189 #endif
190  _handle = 0;
191  _path.clear();
192  }
193  }
194  /// Unloads a shared library.
195 
196  bool isLoaded() const
197  {
198  return _handle!=0;
199  }
200  /// Returns true iff a library has been loaded.
201 
202  bool hasSymbol(const std::string& name)
203  {
204  return getSymbol(name)!=0;
205  }
206  /// Returns true iff the loaded library contains
207  /// a symbol with the given name.
208 
209  void* getSymbol(const std::string& name)
210  {
211  WriteMutex lock(_mutex);
212 
213  void* result = 0;
214  if (_handle)
215  {
216 #if (defined(_WIN32) || defined(_WIN64)) && !defined(__CYGWIN__)// Windows
217  return (void*) GetProcAddress((HMODULE) _handle, name.c_str());
218 #else
219  result = dlsym(_handle, name.c_str());
220 #endif
221  }
222  return result;
223  }
224  /// Returns the address of the symbol with
225  /// the given name. For functions, this
226  /// is the entry point of the function.
227  /// Throws a NotFoundException if the symbol
228  /// does not exist.
229 
230  const std::string& getPath() const
231  {
232  return _path;
233  }
234  /// Returns the path of the library, as
235  /// specified in a call to load() or the
236  /// constructor.
237 
238  static std::string suffix()
239  {
240 #if defined(__APPLE__)
241  return ".dylib";
242 #elif defined(hpux) || defined(_hpux)
243  return ".sl";
244 #elif defined(WIN32) || defined(WIN64)
245  return ".dll";
246 #else
247  return ".so";
248 #endif
249  }
250  /// Returns the platform-specific filename suffix
251  /// for shared libraries (including the period).
252  /// In debug mode, the suffix also includes a
253  /// "d" to specify the debug version of a library.
254 
255 private:
257  SharedLibrary& operator = (const SharedLibrary&);
258  MutexRW _mutex;
259  std::string _path;
260  void* _handle;
261 };
262 typedef std::shared_ptr<SharedLibrary> SharedLibraryPtr;
263 
264 
265 } // namespace GSLAM
266 
267 
268 #endif
bool isLoaded() const
Unloads a shared library.
Definition: SharedLibrary.h:196
const std::string & getPath() const
Returns the address of the symbol with the given name. For functions, this is the entry point of the ...
Definition: SharedLibrary.h:230
virtual ~SharedLibrary()
Creates a SharedLibrary object and loads a library from the given path.
Definition: SharedLibrary.h:131
SharedLibrary(const std::string &path)
Creates a SharedLibrary object.
Definition: SharedLibrary.h:124
void * getSymbol(const std::string &name)
Returns true iff the loaded library contains a symbol with the given name.
Definition: SharedLibrary.h:209
The SharedLibrary class dynamically loads shared libraries at run-time.
Definition: SharedLibrary.h:109
Definition: Camera.h:45
static std::string suffix()
Returns the path of the library, as specified in a call to load() or the constructor.
Definition: SharedLibrary.h:238
bool hasSymbol(const std::string &name)
Returns true iff a library has been loaded.
Definition: SharedLibrary.h:202
void unload()
Loads a shared library from the given path. Throws a LibraryAlreadyLoadedException if a library has a...
Definition: SharedLibrary.h:179
bool load(const std::string &path, int flags=0)
Destroys the SharedLibrary. The actual library remains loaded.
Definition: SharedLibrary.h:142