1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_LITE_SHARED_LIBRARY_H_
16 #define TENSORFLOW_LITE_SHARED_LIBRARY_H_
17 
18 #if defined(_WIN32)
19 // Windows does not have dlfcn.h/dlsym, use GetProcAddress() instead.
20 #include <windows.h>
21 #else
22 #include <dlfcn.h>
23 #endif  // defined(_WIN32)
24 
25 namespace tflite {
26 
27 // SharedLibrary provides a uniform set of APIs across different platforms to
28 // handle dynamic library operations
29 class SharedLibrary {
30  public:
31 #if defined(_WIN32)
LoadLibrary(const char * lib)32   static inline void* LoadLibrary(const char* lib) {
33     return ::LoadLibrary(lib);
34   }
GetLibrarySymbol(void * handle,const char * symbol)35   static inline void* GetLibrarySymbol(void* handle, const char* symbol) {
36     return reinterpret_cast<void*>(
37         GetProcAddress(static_cast<HMODULE>(handle), symbol));
38   }
39   // Warning: Unlike dlsym(RTLD_DEFAULT), it doesn't search the symbol from
40   // dependent DLLs.
GetSymbol(const char * symbol)41   static inline void* GetSymbol(const char* symbol) {
42     return reinterpret_cast<void*>(GetProcAddress(nullptr, symbol));
43   }
UnLoadLibrary(void * handle)44   static inline int UnLoadLibrary(void* handle) {
45     return FreeLibrary(static_cast<HMODULE>(handle));
46   }
GetError()47   static inline const char* GetError() { return "Unknown"; }
48 #else
49   static inline void* LoadLibrary(const char* lib) {
50     return dlopen(lib, RTLD_LAZY | RTLD_LOCAL);
51   }
52   static inline void* GetLibrarySymbol(void* handle, const char* symbol) {
53     return dlsym(handle, symbol);
54   }
55   static inline void* GetSymbol(const char* symbol) {
56     return dlsym(RTLD_DEFAULT, symbol);
57   }
58   static inline int UnLoadLibrary(void* handle) { return dlclose(handle); }
59   static inline const char* GetError() { return dlerror(); }
60 #endif  // defined(_WIN32)
61 };
62 
63 }  // namespace tflite
64 
65 #endif  // TENSORFLOW_LITE_SHARED_LIBRARY_H_
66