DLLWrapper

 
#ifndef PJ_DLLWRAPPER_H
#define PJ_DLLWRAPPER_H
#include <string>
#include <windows.h>
/// A (Windows) DLL wrapper class that takes care of loading and
/// freeing the used library.
/// @author Peter Jansson http://peter.jansson.net
class DllWrapper
{
   public:
      /// Construct a DLL wrapper instance.
      /// The DLL named by the paramater is loaded.
      /// @param DllName The name of the DLL to load.
      DllWrapper(const std::string & DllName);
      /// Destroy this instance. The DLL loaded will be free'd.
      ~DllWrapper();
      /// Get a procedure from the wrapped DLL.
      /// @param Name The name of the procedure wanted.
      FARPROC GetProcedure(const std::string & Name) const;
   private:
      /// Copy construction is not allowed.
      DllWrapper(const DllWrapper & source);
      /// Assigment is not allowed.
      DllWrapper & operator=(const DllWrapper & source);
      /// The handle to the DLL.
      const HMODULE Handle;
      /// The name of the DLL loaded in this wrapper.
      const std::string DllName;
};
#endif
 

Implementation follows:

 
#include "DllWrapper.h"
#include <stdexcept>
DllWrapper::DllWrapper(const std::string & DllName):
   Handle(LoadLibraryA(DllName.c_str())),
   DllName(DllName) {
      if(Handle==NULL)
      {
         throw std::runtime_error("Failed to load the DLL named \""
               +DllName+"\".");
      }
   }
DllWrapper::~DllWrapper() {
   FreeLibrary(Handle);
}
FARPROC DllWrapper::GetProcedure(const std::string & Name) const
{
   FARPROC proc(GetProcAddress(Handle,Name.c_str()));
   if( NULL == proc )
   {
      throw std::runtime_error("Could not find the address for the "
            " procedure \""+Name+"\" in the DLL \""+DllName+"\".");
   }
   return proc;
}
 

Inlägg (RSS) och Kommentarer (RSS).

 


Advertisements:
Cheap Electricity - Loans - Credit Cards - Loans