分享一个动态加载类

可以执行任意导出参数的导出函数

#ifndef __DynamicLibrary_H
#define __DynamicLibrary_H
#include <windows.h>
#include <string>
#include <functional>

class DynamicLibraryT final
{
public:
    DynamicLibraryT(const DynamicLibraryT& other) = delete;
    DynamicLibraryT& operator=(const DynamicLibraryT& other) = delete;

    DynamicLibraryT();
    DynamicLibraryT(const std::string& path);
    ~DynamicLibraryT();

public:
    bool LoadLibrary(const std::string& path);
    bool FreeLibrary();
    template<class r , class... ARGS_TYPES>
    std::function<r(ARGS_TYPES...)> GetProcAddress(const std::string& funcName);
 
private:
    HMODULE mod_;
    std::string path_;
};

template<class r, class... ARGS_TYPES>
std::function<r(ARGS_TYPES...)> DynamicLibraryT::GetProcAddress(const std::string& funcName)
{
    using func_imp = r(*)(ARGS_TYPES...);

    std::function<r(ARGS_TYPES...)> f;
    if (mod_)
    {
        func_imp f_ptr = (func_imp)::GetProcAddress(mod_, funcName.c_str());
        if (f_ptr)
        {
            f = f_ptr;
        }
    }

    return std::move(f);
}

#endif //__DynamicLibrary_H



#include "pch.h"
#include "DynamicLibraryT.h"

DynamicLibraryT::DynamicLibraryT() : DynamicLibraryT("")
{

}

DynamicLibraryT::DynamicLibraryT(const std::string& path) :
    mod_(nullptr) ,
    path_(path)
{
    if (path_.size())
    {
        LoadLibrary(path_);
    }
}

DynamicLibraryT::~DynamicLibraryT()
{
    FreeLibrary();
}

bool DynamicLibraryT::LoadLibrary(const std::string& path)
{
    if (mod_)
    {
        return true;
    }

    if (path.size())
    {
        path_ = path;
        mod_ = ::LoadLibraryExA(path.c_str(), 0, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
    }

    return mod_ ? true : false;
}

bool DynamicLibraryT::FreeLibrary()
{
    bool b = false;
    if (mod_)
    {
        b = (bool)::FreeLibrary(mod_);
        if (b)
        {
            mod_ = nullptr;
        }
    }

    return b;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值