Re: [问题] dynamic shared library设计问题

楼主: PkmX (阿猫)   2017-10-07 22:11:27
我觉得这个直接拿个例子来解释如何在执行时加载 C++ shared library,
并建构和操作 DSO 内定义的 class 和 function:
==============================================================================
// foo.hpp
struct foo {
virtual ~foo() = 0;
virtual auto vfn() const -> int = 0;
auto fn() const -> int;
};
inline foo::~foo() = default;
template<typename... Ts>
using make_foo_fn = auto (*)(Ts...) -> foo*;
==============================================================================
// foo.cpp
#include "foo.hpp"
struct foo_impl : foo {
virtual ~foo_impl() = default;
virtual auto vfn() const -> int override { return fn(); }
};
extern "C" {
auto new_foo() -> foo* { return new foo_impl; }
}
==============================================================================
// main.cpp
#include <cassert>
#include <iostream>
#include <memory>
#include <dlfcn.h>
#include "foo.hpp"
// C++17 scopeguard utility
#include <type_traits>
template<typename F>
struct scopeguard : F {
scopeguard(scopeguard&&) = delete;
~scopeguard() { (*this)(); }
};
template<typename F> scopeguard(F) -> scopeguard<std::decay_t<F>>;
#define PP_CAT_IMPL(x, y) x##y
#define PP_CAT(x, y) PP_CAT_IMPL(x, y)
#define at_scope_exit \
[[maybe_unused]] const auto PP_CAT(sg$, __COUNTER__) = scopeguard
auto foo::fn() const -> int { return 42; }
int main() try {
auto libfoo = dlopen("./libfoo.so", RTLD_NOW | RTLD_GLOBAL);
assert(libfoo);
at_scope_exit { [&] { dlclose(libfoo); } };
const auto new_foo =
reinterpret_cast<make_foo_fn<>>(dlsym(libfoo, "new_foo"));
assert(new_foo);
const auto f = std::unique_ptr<foo>{new_foo()};
std::cout << f->vfn() << std::endl;
} catch (...) { throw; }
==============================================================================
$ GXX='g++ -std=c++17 -Wall -Wextra -pedantic -O2'
$ ${GXX} -fPIC -shared foo.cpp -o libfoo.so
$ ${GXX} -rdynamic main.cpp -ldl
$ ./a.out
42
线上版:http://coliru.stacked-crooked.com/a/0f8900f100523fc7
这里在 foo.hpp 里面宣告 foo 为一个 abstract class 并定义 foo 的 interface,
main() 可以透过这个 interface 操作 foo,
而 foo 的实做 foo_impl 定义在 foo.cpp 里面,
并编译成 libfoo.so 让 main() 透过 dlopen("path/to/libfoo.so", ...) 加载,
但这会有一个问题,main() 根本就不知道 foo_impl 的存在,
所以 foo.cpp 会定义一个 make_foo 的 function 回传一个 foo*,
而 main() 可以用 dlsym(..., "make_foo"); 拿到 foo*,
并透过呼叫 foo 的 virtual function 就可以 dispatch 到 foo_impl 的实做
这里更有趣的就是:
foo_impl::vfn() 会呼叫 foo::fn() 这个不是 virtual 的 function,
而且他的定义在 main.cpp 里面 (当然也有可能是别的 translation unit),
所以 libfoo.so 是看不到 foo:fn() 的定义的,
而 link 的时候要加上 -rdynamic (也就是 ld 的
作者: xam (听说)   2017-10-07 23:00:00
我觉得看得懂这篇的话, 没道理google找的看不懂..
作者: Bencrie   2017-10-07 23:10:00
推详解 XD
作者: stucode   2017-10-07 23:17:00
推,这要解释清楚真的需要一点篇幅。
作者: mabinogi805 (焚离)   2017-10-08 00:03:00
也太详细QQ
作者: dreamboat66 (小嫩)   2017-10-08 02:37:00
谢谢详细的解说,努力理解中

Links booklink

Contact Us: admin [ a t ] ucptt.com