xref: /aosp_15_r20/external/cronet/base/scoped_native_library.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_SCOPED_NATIVE_LIBRARY_H_
6 #define BASE_SCOPED_NATIVE_LIBRARY_H_
7 
8 #include "base/base_export.h"
9 #include "base/native_library.h"
10 #include "base/scoped_generic.h"
11 
12 namespace base {
13 
14 class FilePath;
15 
16 struct BASE_EXPORT NativeLibraryTraits {
17   // It's assumed that this is a fast inline function with little-to-no
18   // penalty for duplicate calls. This must be a static function even
19   // for stateful traits.
InvalidValueNativeLibraryTraits20   static NativeLibrary InvalidValue() { return nullptr; }
21 
22   // This free function will not be called if library == InvalidValue()!
23   static void Free(NativeLibrary library);
24 };
25 
26 // A class which encapsulates a base::NativeLibrary object available only in a
27 // scope.
28 // This class automatically unloads the loaded library in its destructor.
29 class BASE_EXPORT ScopedNativeLibrary
30     : public ScopedGeneric<NativeLibrary, NativeLibraryTraits> {
31  public:
32   // Initializes with a NULL library.
33   ScopedNativeLibrary();
34 
35   // Takes ownership of the given library handle.
36   explicit ScopedNativeLibrary(NativeLibrary library);
37 
38   // Opens the given library and manages its lifetime.
39   explicit ScopedNativeLibrary(const FilePath& library_path);
40 
41   // Move constructor. Takes ownership of handle stored in |scoped_library|
42   ScopedNativeLibrary(ScopedNativeLibrary&& scoped_library);
43 
44   // Move assignment operator. Takes ownership of handle stored in
45   // |scoped_library|.
46   ScopedNativeLibrary& operator=(ScopedNativeLibrary&& scoped_library) =
47       default;
48 
49   ScopedNativeLibrary(const ScopedNativeLibrary&) = delete;
50   ScopedNativeLibrary& operator=(const ScopedNativeLibrary&) = delete;
51 
52   ~ScopedNativeLibrary() override;
53 
54   void* GetFunctionPointer(const char* function_name) const;
55 
56   const NativeLibraryLoadError* GetError() const;
57 
58  private:
59   NativeLibraryLoadError error_;
60 };
61 
62 }  // namespace base
63 
64 #endif  // BASE_SCOPED_NATIVE_LIBRARY_H_
65