refcounting_api.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. //[plugcpp_my_plugin_refcounting_api
  8. #include "../tutorial_common/my_plugin_api.hpp"
  9. #include <boost/dll/config.hpp>
  10. class my_refcounting_api: public my_plugin_api {
  11. public:
  12. // Returns path to shared object that holds a plugin.
  13. // Must be instantiated in plugin.
  14. virtual boost::dll::fs::path location() const = 0;
  15. };
  16. //]
  17. //[plugcpp_library_holding_deleter_api_bind
  18. #include <boost/shared_ptr.hpp>
  19. #include <boost/make_shared.hpp>
  20. #include <boost/dll/shared_library.hpp>
  21. struct library_holding_deleter {
  22. boost::shared_ptr<boost::dll::shared_library> lib_;
  23. void operator()(my_refcounting_api* p) const {
  24. delete p;
  25. }
  26. };
  27. inline boost::shared_ptr<my_refcounting_api> bind(my_refcounting_api* plugin) {
  28. // getting location of the shared library that holds the plugin
  29. boost::dll::fs::path location = plugin->location();
  30. // `make_shared` is an efficient way to create a shared pointer
  31. boost::shared_ptr<boost::dll::shared_library> lib
  32. = boost::make_shared<boost::dll::shared_library>(location);
  33. library_holding_deleter deleter;
  34. deleter.lib_ = lib;
  35. return boost::shared_ptr<my_refcounting_api>(
  36. plugin, deleter
  37. );
  38. }
  39. //]
  40. //[plugcpp_get_plugin_refcounting
  41. #include <boost/dll/import.hpp>
  42. #include <boost/function.hpp>
  43. inline boost::shared_ptr<my_refcounting_api> get_plugin(
  44. boost::dll::fs::path path, const char* func_name)
  45. {
  46. typedef my_refcounting_api*(func_t)();
  47. boost::function<func_t> creator = boost::dll::import_alias<func_t>(
  48. path,
  49. func_name,
  50. boost::dll::load_mode::append_decorations // will be ignored for executable
  51. );
  52. // `plugin` does not hold a reference to shared library. If `creator` will go out of scope,
  53. // then `plugin` can not be used.
  54. my_refcounting_api* plugin = creator();
  55. // Returned variable holds a reference to
  56. // shared_library and it is safe to use it.
  57. return bind( plugin );
  58. // `creator` goes out of scope here and will be destroyed.
  59. }
  60. //]