smart_lib.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2016 Klemens D. Morgenstern.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include "../b2_workarounds.hpp" // contains dll_test::replace_with_full_path
  7. //[smart_lib_setup
  8. #include <boost/dll/smart_library.hpp> // for import_alias
  9. #include <iostream>
  10. #include <memory>
  11. namespace dll = boost::dll;
  12. struct alias;
  13. int main(int argc, char* argv[]) {
  14. /*<-*/ b2_workarounds::argv_to_path_guard guard(argc, argv); /*->*/
  15. boost::dll::fs::path lib_path(argv[1]); // argv[1] contains path to directory with our plugin library
  16. dll::smart_lib lib(lib_path); // smart library instance
  17. //]
  18. //[smart_lib_size
  19. auto size_f = lib.get_function<std::size_t()>("space::my_plugin::size"); //get the size function
  20. auto size = size_f(); // get the size of the class
  21. std::unique_ptr<char[], size> buffer(new char[size]); //allocate a buffer for the import
  22. alias & inst = *reinterpret_cast<alias*>(buffer.get()); //cast it to our alias type.
  23. //]
  24. //[smart_lib_type_alias
  25. lib.add_type_alias("space::my_plugin"); //add an alias, so i can import a class that is not declared here
  26. //]
  27. //[smart_lib_ctor
  28. auto ctor = lib.get_constructor<alias(const std::string&)>(); //get the constructor
  29. ctor.call_standard(&inst, "MyName"); //call the non-allocating constructor. The allocating-constructor is a non-portable feature
  30. //]
  31. //[smart_lib_name
  32. auto name_f = lib.get_mem_fn<const alias, std::string()>("name");//import the name function
  33. std::cout << "Name Call: " << (inst.*name_f)() << std::endl;
  34. //]
  35. //[smart_lib_calculate
  36. //import both calculate functions
  37. auto calc_f = lib.get_mem_fn<alias, float(float, float)>("calculate");
  38. auto calc_i = lib.get_mem_fn<alias, int(int, int)> ("calculate");
  39. std::cout << "calc(float): " << (inst.*calc_f)(5., 2.) << std::endl;
  40. std::cout << "calc(int) : " << (inst.*calc_f)(5, 2) << std::endl;
  41. //]
  42. //[smart_lib_var
  43. auto & var = lib.get_variable<int>("space::my_plugin::value");
  44. cout << "value " << var << endl;
  45. //]
  46. //[smart_lib_dtor
  47. auto dtor = lib.get_destructor<alias>(); //get the destructor
  48. dtor.call_standard(&inst);
  49. std::cout << "plugin->calculate(1.5, 1.5) call: " << plugin->calculate(1.5, 1.5) << std::endl;
  50. }
  51. //]