tutorial9.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2015-2019 Antony Polukhin.
  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 <boost/predef/os.h>
  7. #if BOOST_OS_WINDOWS
  8. //[callplugcpp_tutorial9
  9. #include <boost/dll/import.hpp> // for dll::import
  10. #include <boost/dll/shared_library.hpp> // for dll::shared_library
  11. #include <boost/function.hpp>
  12. #include <iostream>
  13. #include <windows.h>
  14. namespace dll = boost::dll;
  15. int main() {
  16. typedef HANDLE(__stdcall GetStdHandle_t)(DWORD ); // function signature with calling convention
  17. // OPTION #0, requires C++11 compatible compiler that understands GetStdHandle_t signature.
  18. /*<-*/
  19. #if defined(_MSC_VER) && !defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) && !defined(BOOST_NO_CXX11_DECLTYPE) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) /*->*/
  20. auto get_std_handle = dll::import<GetStdHandle_t>(
  21. "Kernel32.dll",
  22. "GetStdHandle",
  23. boost::dll::load_mode::search_system_folders
  24. );
  25. std::cout << "0.0 GetStdHandle() returned " << get_std_handle(STD_OUTPUT_HANDLE) << std::endl;
  26. // You may put the `get_std_handle` into boost::function<>. But boost::function<Signature> can not compile with
  27. // Signature template parameter that contains calling conventions, so you'll have to remove the calling convention.
  28. boost::function<HANDLE(DWORD)> get_std_handle2 = get_std_handle;
  29. std::cout << "0.1 GetStdHandle() returned " << get_std_handle2(STD_OUTPUT_HANDLE) << std::endl;
  30. /*<-*/
  31. #endif /*->*/
  32. // OPTION #1, does not require C++11. But without C++11 dll::import<> can not handle calling conventions,
  33. // so you'll need to hand write the import.
  34. dll::shared_library lib("Kernel32.dll", dll::load_mode::search_system_folders);
  35. GetStdHandle_t& func = lib.get<GetStdHandle_t>("GetStdHandle");
  36. // Here `func` does not keep a reference to `lib`, you'll have to deal with that on your own.
  37. std::cout << "1.0 GetStdHandle() returned " << func(STD_OUTPUT_HANDLE) << std::endl;
  38. return 0;
  39. }
  40. //]
  41. #else // BOOST_WINDOWS
  42. #include <boost/dll/shared_library.hpp> // for dll::shared_library
  43. int main() {
  44. return 0;
  45. }
  46. #endif // BOOST_WINDOWS