comparison C++/DynLib.h @ 195:42b77e0161d0

Add a dynamic library loader
author David Demelier <markand@malikania.fr>
date Wed, 27 Nov 2013 21:20:26 +0100
parents
children 274b4f216e65
comparison
equal deleted inserted replaced
194:9fc5f917872b 195:42b77e0161d0
1 /*
2 * DynLib.h -- portable shared library loader
3 *
4 * Copyright (c) 2013 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #ifndef _DYN_LIB_H_
20 #define _DYN_LIB_H_
21
22 #include <string>
23
24 /**
25 * @class DynLib
26 * @brief Load a dynamic module
27 *
28 * This class is a portable wrapper to load shared libraries on
29 * supported systems.
30 */
31 class DynLib {
32 public:
33 #if defined(_MSC_VER)
34 #else
35 using Handle = void *;
36 using Sym = void *;
37 #endif
38
39 enum Policy {
40 Immediately, //! load symbols immediately
41 Lazy //! load symbols when needed
42 };
43
44 private:
45 Handle m_handle;
46
47 void systemInit();
48 Handle systemLoad(const std::string &path, Policy policy) const;
49 Sym systemSym(const std::string &name);
50 void systemClose();
51
52 public:
53 /**
54 * Copy is forbidden.
55 */
56 DynLib(const DynLib &) = delete;
57 DynLib &operator=(const DynLib &) = delete;
58
59 /**
60 * Default constructor.
61 */
62 DynLib();
63
64 /**
65 * Constructor to load a shared module. The path must
66 * be absolute.
67 *
68 * @param path the absolute path
69 * @param policy the policy to load
70 * @throw std::runtime_error on error
71 */
72 DynLib(const std::string &path,
73 Policy policy = Immediately);
74
75 /**
76 * Close the library automatically.
77 */
78 ~DynLib();
79
80 /**
81 * Get a symbol from the library.
82 *
83 * @param name the symbol
84 * @return the symbol
85 * @throw std::runtime_error on error
86 * @throw std::out_of_range if not found
87 */
88 template <typename T>
89 T sym(const std::string &name)
90 {
91 return reinterpret_cast<T>(systemSym(name));
92 }
93 };
94
95 #endif // !_DYN_LIB_H_