Savarese Software Research Corporation
DynamicLibrary.h
Go to the documentation of this file.
00001 /*
00002  * Copyright 2006-2009 Savarese Software Research Corporation
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     https://www.savarese.com/software/ApacheLicense-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00022 #ifndef __SSRC_WSPR_UTILITY_DYNAMC_LIBRARY_H
00023 #define __SSRC_WSPR_UTILITY_DYNAMC_LIBRARY_H
00024 
00025 namespace NS_POSIX {
00026 #include <dlfcn.h>
00027 }
00028 
00029 #include <ssrc/wispers/utility/LoadError.h>
00030 
00031 __BEGIN_NS_SSRC_WSPR_UTILITY
00032 
00033 class DynamicLibrary {
00034   std::string _filename;
00035   void *_handle;
00036 
00037 public:
00038 
00039   enum Mode {
00040     LazyLocal  = RTLD_LAZY | RTLD_LOCAL,
00041     LazyGlobal = RTLD_LAZY | RTLD_GLOBAL,
00042     NowLocal   = RTLD_NOW | RTLD_LOCAL,
00043     NowGlobal  = RTLD_NOW | RTLD_GLOBAL
00044   };
00045 
00046   explicit
00047   DynamicLibrary(const std::string & filename, const Mode mode = LazyLocal)
00048     SSRC_DECL_THROW(LoadError) :
00049     _filename(filename), _handle(NS_POSIX::dlopen(filename.c_str(), mode))
00050   {
00051     if(!_handle) {
00052       std::string error;
00053       const char *message = NS_POSIX::dlerror();
00054       if(message)
00055         error.append(message);
00056       else
00057         error.append("DynamicLibrary load error: ").append(filename);
00058       throw LoadError(error);
00059     }
00060   }
00061 
00062   virtual ~DynamicLibrary() {
00063     NS_POSIX::dlclose(_handle);
00064   }
00065 
00066   std::string filename() const {
00067     return _filename;
00068   }
00069 
00070   void * symbol(const std::string & name) {
00071     return NS_POSIX::dlsym(_handle, name.c_str());
00072   }
00073 
00074   template<typename T>
00075   T symbol(const std::string & name) {
00076     return reinterpret_cast<T>(symbol(name));
00077   }
00078 };
00079 
00080 __END_NS_SSRC_WSPR_UTILITY
00081 
00082 #endif

Savarese Software Research Corporation
Copyright © 2006-2011 Savarese Software Research Corporation. All rights reserved.