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

source code of boost/libs/dll/example/getting_started.cpp