Boost C++ 库

这是世界上最受推崇、设计最精良的 C++ 库项目之一。 Herb SutterAndrei Alexandrescu, C++ Coding Standards

入门 - Boost C++ 函数库
PrevUpHomeNext

Boost.DLL 是一个仅头文件库。要开始使用该库,您只需要包含 <boost/dll.hpp> 头文件。之后,您就可以自由地导入和导出函数和变量。 boost::dll::import* 函数需要链接 boost_filesystemboost_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");

现在您可以使用 getget_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_locationboost::dll::this_line_locationboost::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<>
}

import<T>(...)

// 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;
}

import<T>(...)

// 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_alias<T>(...)

BOOST_DLL_ALIAS

import<T>(...)import_alias<T>(...) 函数返回的变量会内部保持对共享库的引用,因此使用导入的变量或函数是安全的。

BOOST_SYMBOL_EXPORT 只是 Boost.Config 中的一个宏,它展开为 __declspec(dllexport)__attribute__((visibility("default")))。您可以自由地使用自己的宏进行导出。

[Note] 注意

在 Linux/POSIX/MacOS 上,请链接 "dl" 库。同时建议使用 "-fvisibility=hidden" 标志。


PrevUpHomeNext