SharedLibrary.hpp revision a230805e1fb8d9da59c706ba13aed2a9f3410c1e
1// SwiftShader Software Renderer 2// 3// Copyright(c) 2005-2012 TransGaming Inc. 4// 5// All rights reserved. No part of this software may be copied, distributed, transmitted, 6// transcribed, stored in a retrieval system, translated into any human or computer 7// language by any means, or disclosed to third parties without the explicit written 8// agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express 9// or implied, including but not limited to any patent rights, are granted to you. 10// 11 12#ifndef SharedLibrary_hpp 13#define SharedLibrary_hpp 14 15#if defined(_WIN32) 16 #include <Windows.h> 17#else 18 #include <dlfcn.h> 19#endif 20 21void *getLibraryHandle(const char *path); 22void *loadLibrary(const char *path); 23 24template<int n> 25void *loadLibrary(const char *(&names)[n]) 26{ 27 for(int i = 0; i < n; i++) 28 { 29 void *library = getLibraryHandle(names[i]); 30 31 if(library) 32 { 33 return library; 34 } 35 } 36 37 for(int i = 0; i < n; i++) 38 { 39 void *library = loadLibrary(names[i]); 40 41 if(library) 42 { 43 return library; 44 } 45 } 46 47 return 0; 48} 49 50#if defined(_WIN32) 51 inline void *loadLibrary(const char *path) 52 { 53 return (void*)LoadLibrary(path); 54 } 55 56 inline void *getLibraryHandle(const char *path) 57 { 58 HMODULE module = 0; 59 GetModuleHandleEx(0, path, &module); 60 return (void*)module; 61 } 62 63 inline void freeLibrary(void *library) 64 { 65 FreeLibrary((HMODULE)library); 66 } 67 68 inline void *getProcAddress(void *library, const char *name) 69 { 70 return (void*)GetProcAddress((HMODULE)library, name); 71 } 72#else 73 inline void *loadLibrary(const char *path) 74 { 75 return dlopen(path, RTLD_LAZY); 76 } 77 78 inline void *getLibraryHandle(const char *path) 79 { 80 #ifdef __ANDROID__ 81 // bionic doesn't support RTLD_NOLOAD before L 82 return dlopen(path, RTLD_NOW); 83 #else 84 void *resident = dlopen(path, RTLD_LAZY | RTLD_NOLOAD); 85 86 if(resident) 87 { 88 return dlopen(path, RTLD_LAZY); // Increment reference count 89 } 90 91 return 0; 92 #endif 93 } 94 95 inline void freeLibrary(void *library) 96 { 97 if(library) 98 { 99 dlclose(library); 100 } 101 } 102 103 inline void *getProcAddress(void *library, const char *name) 104 { 105 return library ? dlsym(library, name) : 0; 106 } 107#endif 108 109#endif // SharedLibrary_hpp 110