Advertisement
WeltEnSTurm

Untitled

May 27th, 2013
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.59 KB | None | 0 0
  1.  
  2. module ws.sys.library;
  3.  
  4. import std.string;
  5. import std.conv;
  6.  
  7. version(Windows) import derelict.util.wintypes;
  8. version(Posix) import std.c.linux.linux;
  9.  
  10. class Library {
  11.  
  12.     void* get(string s){
  13.         void* p = null;
  14.         version(Windows)
  15.             p = GetProcAddress(lib, s.toStringz);
  16.         version(Posix)
  17.             p = dlsym(lib, s.toStringz);
  18.         if(!p)
  19.             throw new Exception("Failed to load symbol \"" ~ s ~ "\": " ~ getError);
  20.         return p;
  21.     }
  22.    
  23.     T call(T, Args...)(string name, Args args){
  24.         auto func = cast(T function(Args))get(name);
  25.         return func(args);
  26.     }
  27.  
  28.     this(string s, string vers = ""){
  29.         version(Windows)
  30.             lib = LoadLibraryA(s.toStringz);
  31.         version(Posix)
  32.             lib = dlopen(("lib" ~ s ~ ".so" ~ vers).toStringz, RTLD_NOW);
  33.         if(!lib)
  34.             throw new Exception("Failed to load library \"" ~ s ~ "\": " ~ getError);
  35.     }
  36.  
  37.  
  38.     ~this(){
  39.         version(Windows)
  40.             FreeLibrary(lib);
  41.         version(Posix)
  42.             dlclose(lib);
  43.     }
  44.  
  45.     version(Windows) private HMODULE lib;
  46.     version(Posix) private void* lib;
  47.  
  48.     private string getError(){
  49.         version(Windows){
  50.             DWORD errcode = GetLastError();
  51.             LPCSTR msgBuf;
  52.             DWORD i = FormatMessageA(
  53.                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
  54.                 FORMAT_MESSAGE_FROM_SYSTEM |
  55.                 FORMAT_MESSAGE_IGNORE_INSERTS,
  56.                 null,
  57.                 errcode,
  58.                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  59.                 cast(LPCSTR)&msgBuf,
  60.                 0,
  61.                 null);
  62.             string text = to!string(msgBuf);
  63.             LocalFree(cast(HLOCAL)msgBuf);
  64.             if(i >= 2)
  65.                 i -= 2;
  66.             return text[0 .. i];
  67.         }version(Posix){
  68.             auto err = dlerror();
  69.             if(!err)
  70.                 return "Unknown Error";
  71.             return to!string(err);     
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement