getting_started.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #include <boost/core/lightweight_test.hpp>
  8. #include <boost/dll.hpp>
  9. #include <boost/function.hpp>
  10. #include <string>
  11. #include "b2_workarounds.hpp"
  12. // Unit Tests
  13. int main(int argc, char* argv[]) {
  14. using namespace boost;
  15. boost::dll::fs::path path_to_shared_library = b2_workarounds::first_lib_from_argv(argc, argv);
  16. BOOST_TEST(path_to_shared_library.string().find("getting_started_library") != std::string::npos);
  17. //[getting_started_imports_c_function
  18. // Importing pure C function
  19. function<int(int)> c_func = dll::import<int(int)>(
  20. path_to_shared_library, "c_func_name"
  21. );
  22. //]
  23. int c_func_res = c_func(1); // calling the function
  24. BOOST_TEST(c_func_res == 2);
  25. //[getting_started_imports_c_variable
  26. // Importing pure C variable
  27. shared_ptr<int> c_var = dll::import<int>(
  28. path_to_shared_library, "c_variable_name"
  29. );
  30. //]
  31. int c_var_old_contents = *c_var; // using the variable
  32. *c_var = 100;
  33. BOOST_TEST(c_var_old_contents == 1);
  34. //[getting_started_imports_alias
  35. // Importing function by alias name
  36. /*<-*/ function<std::string(const std::string&)> /*->*/ /*=auto*/ cpp_func = dll::import_alias<std::string(const std::string&)>(
  37. path_to_shared_library, "pretty_name"
  38. );
  39. //]
  40. // calling the function
  41. std::string cpp_func_res = cpp_func(std::string("In importer."));
  42. BOOST_TEST(cpp_func_res == "In importer. Hello from lib!");
  43. #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_AUTO_DECLARATIONS)
  44. //[getting_started_imports_cpp11_function
  45. // Importing function.
  46. auto cpp11_func = dll::import<int(std::string&&)>(
  47. path_to_shared_library, "i_am_a_cpp11_function"
  48. );
  49. //]
  50. // calling the function
  51. int cpp11_func_res = cpp11_func(std::string("In importer."));
  52. BOOST_TEST(cpp11_func_res == sizeof("In importer.") - 1);
  53. #endif
  54. //[getting_started_imports_cpp_variable
  55. // Importing variable.
  56. shared_ptr<std::string> cpp_var = dll::import<std::string>(
  57. path_to_shared_library, "cpp_variable_name"
  58. );
  59. //]
  60. std::string cpp_var_old_contents = *cpp_var; // using the variable
  61. *cpp_var = "New value";
  62. BOOST_TEST(cpp_var_old_contents == "some value");
  63. BOOST_TEST(*cpp_var == "New value");
  64. return boost::report_errors();
  65. }