经验分享: plugin 以及符号查找

YourOwnPluginLoader.hpp

class YourOwnPluginLoader
{
public:
    explicit YourOwnPluginLoader(const std::string &plugin);
    ~YourOwnPluginLoader() final;
    void *dlsym(const std::string &symbol) final;

private:
    void *handle_ = nullptr;

};

YourOwnPluginLoader.cpp


#include "YourOwnPluginLoader.h"
#include <dlfcn.h>

YourOwnPluginLoader::YourOwnPluginLoader(const std::string &plugin)
{
    std::string full_path = std::string("/usr/lib64/yourown/") + plugin;
    handle_ = dlopen(full_path.c_str(), RTLD_NOW | RTLD_LOCAL);
    if (handle_ == nullptr)
    {
        //err log
    }
}

YourOwnPluginLoader::~YourOwnPluginLoader()
{
    if(handle_ != nullptr) dlclose(handle_);
}

void *YourOwnPluginLoader::dlsym(const std::string &symbol)
{
    if (handle_ == nullptr)
    {
        return nullptr;
    }

    auto ret(::dlsym(handle_, symbol.c_str()));

    return ret;
}

符号查找

plugin加载以及符号查找

template<typename ReturnType, typename... Params>
std::function<ReturnType(Params...)> pluginResolveFunc(const std::string &symbolName,
                                                       const std::string &pluginName) noexcept
{
    typedef std::unordered_map<std::string, std::shared_ptr<YourOwnPluginLoader>> PluginMap;
    static PluginMap plugin_holder;

    std::shared_ptr<YourOwnPluginLoader>instance;

    auto it = plugin_holder.find(pluginName);
    if(it == plugin_holder.end())
    {
        instance = std::make_shared<YourOwnPluginLoader>(pluginName);
        plugin_holder.insert({pluginName, instance});
    } else
    {
        instance = it->second;
    }

    void *ptr(instance->dlsym(symbolName));

    typedef ReturnType (*FunctionType)(Params...);
    FunctionType functionPtr((FunctionType) ptr);
    return std::function<ReturnType(Params...)>(functionPtr);
}

用法样例

假使当前 libyourownpoxyplugin.so里面有一个符号用于创建proxy的instance

extern "C" std::unique_ptr<YourOwnProxyInterface> g_createYourOwnProxyHandler(uint32_t);

        std::unique_ptr<YourOwnProxyInterface>create()
        {
            try
            {
                static auto createHandler =
                    pluginResolveFunc<std::unique_ptr<YourOwnProxyInterface>,uint32_t>(
                        "g_createYourOwnProxyHandler", "libyourownpoxyplugin.so");

                return createHandler(9527);
            }
            catch (const std::exception &e)
            {
                //err log
                return nullptr

            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值