Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #include <sys/types.h>
00018
00019 #include <cstdio>
00020 #include <iostream>
00021 #include <algorithm>
00022
00023 #include "dl_wrapper.h"
00024 #include "g2o/stuff/filesys_tools.h"
00025
00026 #if defined (UNIX) || defined(CYGWIN)
00027 #include <dlfcn.h>
00028 #endif
00029
00030 #ifdef __APPLE__
00031 #define SO_EXT "dylib"
00032 #define SO_EXT_LEN 5
00033 #elif defined (WINDOWS) || defined (CYGWIN)
00034 #define SO_EXT "dll"
00035 #define SO_EXT_LEN 3
00036 #else // Linux
00037 #define SO_EXT "so"
00038 #define SO_EXT_LEN 2
00039 #endif
00040
00041 using namespace std;
00042
00043 namespace g2o {
00044
00045 DlWrapper::DlWrapper()
00046 {
00047 }
00048
00049 DlWrapper::~DlWrapper()
00050 {
00051 clear();
00052 }
00053
00054 int DlWrapper::openLibraries(const std::string& directory, const std::string& pattern)
00055 {
00056 cerr << "# loading libraries from " << directory << "\t pattern: " << pattern << endl;
00057 string searchPattern = directory + "/" + pattern;
00058 if (pattern == "")
00059 searchPattern = directory + "/*";
00060 vector<string> matchingFiles = getFilesByPattern(searchPattern.c_str());
00061
00062 int numLibs = 0;
00063 for (size_t i = 0; i < matchingFiles.size(); ++i) {
00064 const string& filename = matchingFiles[i];
00065 if (find(_filenames.begin(), _filenames.end(), filename) != _filenames.end())
00066 continue;
00067
00068
00069
00070
00071
00072
00073 #ifndef G2O_LIBRARY_POSTFIX
00074 if ((filename.rfind(string("_d.") + SO_EXT) == filename.length() - 3 - SO_EXT_LEN)
00075 || (filename.rfind(string("_rd.") + SO_EXT) == filename.length() - 4 - SO_EXT_LEN)
00076 || (filename.rfind(string("_s.") + SO_EXT) == filename.length() - 3 - SO_EXT_LEN))
00077 continue;
00078 #endif
00079
00080
00081
00082 if (openLibrary(filename))
00083 numLibs++;
00084 }
00085
00086 return numLibs;
00087 }
00088
00089 void DlWrapper::clear()
00090 {
00091 # if defined (UNIX) || defined(CYGWIN)
00092 for (size_t i = 0; i < _handles.size(); ++i) {
00093 dlclose(_handles[i]);
00094 }
00095 #elif defined(WINDOWS)
00096 for (size_t i = 0; i < _handles.size(); ++i) {
00097 FreeLibrary(_handles[i]);
00098 }
00099 #endif
00100 _filenames.clear();
00101 _handles.clear();
00102 }
00103
00104 bool DlWrapper::openLibrary(const std::string& filename)
00105 {
00106 # if defined (UNIX) || defined(CYGWIN)
00107 void* handle = dlopen(filename.c_str(), RTLD_LAZY);
00108 if (! handle) {
00109 cerr << "Cannot open library: " << dlerror() << '\n';
00110 return false;
00111 }
00112 # elif defined (WINDOWS)
00113 HMODULE handle = LoadLibrary(filename.c_str());
00114 if (! handle) {
00115 cerr << "Cannot open library." << endl;
00116 return false;
00117 }
00118 # endif
00119
00120
00121
00122 _filenames.push_back(filename);
00123 _handles.push_back(handle);
00124 return true;
00125 }
00126
00127 }
00128