SharedLibrary.hpp revision e2540106b756159d180677ac9f84da9af49dfd8a
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#if defined(_WIN32)
13	#include <Windows.h>
14#else
15	#include <dlfcn.h>
16#endif
17
18template<int n>
19void *loadLibrary(const char *(&names)[n])
20{
21	for(int i = 0; i < n; i++)
22	{
23		void *library = getLibraryHandle(names[i]);
24
25		if(library)
26		{
27			return library;
28		}
29	}
30
31	for(int i = 0; i < n; i++)
32	{
33		void *library = loadLibrary(names[i]);
34
35		if(library)
36		{
37			return library;
38		}
39	}
40
41	return 0;
42}
43
44#if defined(_WIN32)
45	inline void *loadLibrary(const char *path)
46	{
47		return (void*)LoadLibrary(path);
48	}
49
50	inline void *getLibraryHandle(const char *path)
51	{
52		HMODULE module = 0;
53		GetModuleHandleEx(0, path, &module);
54		return (void*)module;
55	}
56
57	inline void freeLibrary(void *library)
58	{
59		FreeLibrary((HMODULE)library);
60	}
61
62	inline void *getProcAddress(void *library, const char *name)
63	{
64		return (void*)GetProcAddress((HMODULE)library, name);
65	}
66#else
67	inline void *loadLibrary(const char *path)
68	{
69		return dlopen(path, RTLD_LAZY);
70	}
71
72	inline void *getLibraryHandle(const char *path)
73	{
74		bool resident = (dlopen(names[i], RTLD_NOLOAD) != 0);
75
76		if(resident)
77		{
78			return dlopen(path, RTLD_LAZY);   // Increment reference count
79		}
80
81		return 0;
82	}
83
84	inline void freeLibrary(void *library)
85	{
86		dlclose(library);
87	}
88
89	inline void *getProcAddress(void *library, const char *name)
90	{
91		return dlsym(library, name);
92	}
93#endif
94