Line data Source code
1 : // SPDX-License-Identifier: Apache-2.0
2 : /**
3 : * Copyright (C) 2025 Samsung Electronics Co., Ltd. All Rights Reserved.
4 : *
5 : * @file dynamic_library_loader.h
6 : * @date 14 January 2025
7 : * @brief Wrapper for loading dynamic libraries on multiple operating systems
8 : * @see https://github.com/nnstreamer/nntrainer
9 : * @author Grzegorz Kisala <g.kisala@samsung.com>
10 : * @bug No known bugs except for NYI items
11 : *
12 : */
13 :
14 : #ifndef __DYNAMIC_LIBRARY_LOADER__
15 : #define __DYNAMIC_LIBRARY_LOADER__
16 :
17 : #include <string>
18 :
19 : #ifdef _WIN32
20 : #include "windows.h"
21 :
22 : // This flags are not used on windows. Defining those symbols for windows make
23 : // possible using the same external interface for loadLibrary function
24 : #define RTLD_LAZY 0
25 : #define RTLD_NOW 0
26 : #define RTLD_BINDING_MASK 0
27 : #define RTLD_NOLOAD 0
28 : #define RTLD_DEEPBIND 0
29 : #define RTLD_GLOBAL 0
30 : #define RTLD_LOCAL 0
31 : #define RTLD_NODELETE 0
32 :
33 : #else
34 : #include <dlfcn.h>
35 : #endif
36 :
37 : namespace nntrainer {
38 :
39 : /**
40 : * @brief DynamicLibraryLoader wrap process of loading dynamic libraries for
41 : * multiple operating system
42 : *
43 : */
44 : class DynamicLibraryLoader {
45 : public:
46 : static void *loadLibrary(const char *path, [[maybe_unused]] const int flag) {
47 : #if defined(_WIN32)
48 : return LoadLibraryA(path);
49 : #else
50 22 : return dlopen(path, flag);
51 : #endif
52 : }
53 :
54 : static int freeLibrary(void *handle) {
55 : #if defined(_WIN32)
56 : return FreeLibrary((HMODULE)handle);
57 : #else
58 0 : return dlclose(handle);
59 : #endif
60 : }
61 :
62 : static const char *getLastError() {
63 : #if defined(_WIN32)
64 : return std::to_string(GetLastError()).c_str();
65 : #else
66 40 : return dlerror();
67 : #endif
68 : }
69 :
70 : static void *loadSymbol(void *handle, const char *symbol_name) {
71 : #if defined(_WIN32)
72 : return GetProcAddress((HMODULE)handle, symbol_name);
73 : #else
74 18 : return dlsym(handle, symbol_name);
75 : #endif
76 : }
77 : };
78 :
79 : } // namespace nntrainer
80 :
81 : #endif // __DYNAMIC_LIBRARY_LOADER__
|