on_unload_lib.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2014 Renato Tegon Forti, Antony Polukhin.
  2. // Copyright 2015-2019 Antony Polukhin.
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt
  6. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. // MinGW related workaround
  8. #define BOOST_DLL_FORCE_ALIAS_INSTANTIATION
  9. //[plugcpp_on_unload
  10. #include <boost/dll/alias.hpp> // for BOOST_DLL_ALIAS
  11. #include <boost/function.hpp>
  12. #include <vector>
  13. namespace my_namespace {
  14. struct on_unload {
  15. typedef boost::function<void()> callback_t;
  16. typedef on_unload this_type;
  17. ~on_unload() {
  18. for (std::size_t i = 0; i < callbacks_.size(); ++i) {
  19. callback_t& function = callbacks_[i];
  20. function(); // calling the callback
  21. }
  22. }
  23. // not thread safe
  24. static void add(const callback_t& function) {
  25. static this_type instance;
  26. instance.callbacks_.push_back(function);
  27. }
  28. private:
  29. std::vector<callback_t> callbacks_;
  30. on_unload() {} // prohibit construction outside of the `add` function
  31. };
  32. // Exporting the static "add" function with name "on_unload"
  33. BOOST_DLL_ALIAS(my_namespace::on_unload::add, on_unload)
  34. } // namespace my_namespace
  35. //]