cpp-sdl2
C++ header-only SDL2 wrapper
shared_object.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <SDL.h>
4 
5 #include <string>
6 
7 #include "exception.hpp"
8 
9 namespace sdl
10 {
17 {
19  using SharedObjectHandle = void*;
22 
23 public:
25  using FunctionAddress = void*;
26 
29  SharedObject(std::string const& objectName) : handle_{SDL_LoadObject(objectName.c_str())}
30  {
31  if (!handle_) throw Exception("SDL_LoadObject");
32  }
33 
35  SharedObject() = default;
36 
38  ~SharedObject() { SDL_UnloadObject(handle_); }
39 
41  SharedObject(SharedObject&& other) noexcept { *this = std::move(other); }
42 
44  SharedObject& operator=(SharedObject&& other) noexcept
45  {
46  if (handle_ != other.handle_)
47  {
48  // If we currently hold an object
49  if (handle_)
50  {
51  // Free so we do not leak
52  SDL_UnloadObject(handle_);
53  }
54 
55  // Assign from other handle, and set it to null
56  handle_ = other.handle_;
57  other.handle_ = nullptr;
58  }
59 
60  return *this;
61  }
62 
64  SharedObject(SharedObject const&) = delete;
65 
67  SharedObject& operator=(SharedObject const&) = delete;
68 
70  FunctionAddress function_pointer(std::string const& functionName) const
71  {
72  const auto address = SDL_LoadFunction(handle_, functionName.c_str());
73  if (!address) throw Exception("SDL_LoadFunction");
74  return address;
75  }
76 
80  template<typename FunctionPointerSignature>
81  FunctionPointerSignature function_pointer(std::string const& functionName) const
82  {
83  return reinterpret_cast<FunctionPointerSignature>(function_pointer(functionName));
84  }
85 };
86 
87 } // namespace sdl
SharedObject(SharedObject &&other) noexcept
Move ctor.
SharedObject & operator=(SharedObject &&other) noexcept
Move shared object into this one.
void * SharedObjectHandle
Types should be at least named. Alias void* to "SharedObjectHandle*.
FunctionPointerSignature function_pointer(std::string const &functionName) const
Syntactic sugar overload, provide you a way to specify the actual type of the function pointer e...
SharedObjectHandle handle_
This class wrap an handle to a shared object.
Represent a shared object (dynamic library, dynamically loaded library, module, plugin...).
Define to deactivate exception support.
Definition: color.hpp:7
SharedObject(std::string const &objectName)
Get a shared object ( = Load the named library dynamically)
FunctionAddress function_pointer(std::string const &functionName) const
Retrieve the raw address of a function inside the owned object. User has to cast this to the correct ...
void * FunctionAddress
Alias void* to a descriptive "pointer to function" typename.
Define to deactivate exception support.
Definition: exception.hpp:21
~SharedObject()
Automatically unload the library for you.
SharedObject()=default
Construct an empty shared object handler. You can move assign to it.