Boost.DLL 是一个仅头文件库。要开始使用该库,您只需要包含 <boost/dll.hpp>
头文件。之后,您就可以自由地导入和导出函数和变量。 boost::dll::import*
函数需要链接 boost_filesystem
和 boost_system
库,以及一些特定平台的动态加载库,例如 dl
。使用 CMake,这一负担就消失了,因为 find_package(Boost COMPONENTS dll)
提供了一个 Boost::dll
目标,该目标管理与其他库的依赖关系。
如果要加载一个库,只需将库的路径作为参数构造 boost::dll::shared_library
类。
boost::dll::shared_library lib("/test/boost/application/libtest_library.so");
现在您可以使用 get
和 get_alias
成员函数轻松地从该库导入符号。
int plugin_constant = lib.get<const int>("integer_variable"); auto function_ptr = lib.get<int()>("function_returning_int"); int& i = lib.get_alias<int>("alias_to_int_variable");
对于 boost::dll::shared_library
,只有在 boost::dll::shared_library
实例未被销毁之前,使用导入的符号才是安全的。
使用 boost::dll::library_info
查询库,并使用 boost::dll::symbol_location
、boost::dll::this_line_location
和 boost::dll::program_location
获取符号信息。
要导入单个函数或变量,您可以使用以下单行代码。
using namespace boost; // `extern "C"` - specifies C linkage: forces the compiler to export function/variable by a pretty (unmangled) C name. #define API extern "C" BOOST_SYMBOL_EXPORT
导入 (使用 DLL/DSL 的代码) |
导出 (DLL/DSL 源代码) |
函数描述 |
---|---|---|
// Importing function. auto cpp11_func = dll::import_symbol<int(std::string&&)>( path_to_shared_library, "i_am_a_cpp11_function" );
|
namespace some_namespace { API int i_am_a_cpp11_function(std::string&& param) noexcept; // ^-------------------- function name to use in dll::import_symbol<> }
|
|
// Importing variable. std::shared_ptr<std::string> cpp_var = dll::import_symbol<std::string>( path_to_shared_library, "cpp_variable_name" );
|
namespace your_project_namespace { API std::string cpp_variable_name; }
|
|
// Importing function by alias name auto cpp_func = dll::import_alias<std::string(const std::string&)>( path_to_shared_library, "pretty_name" );
|
namespace some_namespace { std::string i_am_function_with_ugly_name(const std::string& param) noexcept; } // When you have no control over function sources or wish to specify another name. BOOST_DLL_ALIAS(some_namespace::i_am_function_with_ugly_name, pretty_name)
|
从 import<T>(...)
和 import_alias<T>(...)
函数返回的变量会内部保持对共享库的引用,因此使用导入的变量或函数是安全的。
BOOST_SYMBOL_EXPORT
只是 Boost.Config 中的一个宏,它展开为 __declspec(dllexport)
或 __attribute__((visibility("default")))
。您可以自由地使用自己的宏进行导出。
![]() |
注意 |
---|---|
在 Linux/POSIX/MacOS 上,请链接 "dl" 库。同时建议使用 "-fvisibility=hidden" 标志。 |