Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module ws.sys.library;
- import std.string;
- import std.conv;
- version(Windows) import derelict.util.wintypes;
- version(Posix) import std.c.linux.linux;
- class Library {
- void* get(string s){
- void* p = null;
- version(Windows)
- p = GetProcAddress(lib, s.toStringz);
- version(Posix)
- p = dlsym(lib, s.toStringz);
- if(!p)
- throw new Exception("Failed to load symbol \"" ~ s ~ "\": " ~ getError);
- return p;
- }
- T call(T, Args...)(string name, Args args){
- auto func = cast(T function(Args))get(name);
- return func(args);
- }
- this(string s, string vers = ""){
- version(Windows)
- lib = LoadLibraryA(s.toStringz);
- version(Posix)
- lib = dlopen(("lib" ~ s ~ ".so" ~ vers).toStringz, RTLD_NOW);
- if(!lib)
- throw new Exception("Failed to load library \"" ~ s ~ "\": " ~ getError);
- }
- ~this(){
- version(Windows)
- FreeLibrary(lib);
- version(Posix)
- dlclose(lib);
- }
- version(Windows) private HMODULE lib;
- version(Posix) private void* lib;
- private string getError(){
- version(Windows){
- DWORD errcode = GetLastError();
- LPCSTR msgBuf;
- DWORD i = FormatMessageA(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- null,
- errcode,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- cast(LPCSTR)&msgBuf,
- 0,
- null);
- string text = to!string(msgBuf);
- LocalFree(cast(HLOCAL)msgBuf);
- if(i >= 2)
- i -= 2;
- return text[0 .. i];
- }version(Posix){
- auto err = dlerror();
- if(!err)
- return "Unknown Error";
- return to!string(err);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement