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