C++使用宏实现动态库加载 c++加载静态库

   2023-02-09 学习力0
核心提示:目录前言一、为什么使用宏1、Windows加载2、Linux加载3、宏加载二、具体实现三、如何使用1、引用头文件2、添加导入宏3、直接调用总结前言开发的时候,有些项目不能静态链接动态库,需要程序运行时加载动态库,这个时候根据不同平台我们通常使用LoadLibrary或d

前言

开发的时候,有些项目不能静态链接动态库,需要程序运行时加载动态库,这个时候根据不同平台我们通常使用LoadLibrary或dlopen将动态库加载到程序中,并且还需要定义函数指针然后在获取函数地址,这一系列的操作其实时比较麻烦的,尤其是方法较多的情况,基本没法这么做,这时候就需要将这一过程进行适当的简化。让动态加载在方法较多的情况下尽量减少工作量。

一、为什么使用宏

一般的动态库加载流程

1、Windows加载

#include<Windows.h>
extern "C"
{
#include "libavformat/avformat.h"
}
//定义方法类型
typedef  AVFormatContext*(*delegate_avformat_alloc_context)(void);
//定义方法指针
delegate_avformat_alloc_context dl_avformat_alloc_context;
HMODULE _hLibrary = nullptr;
//加载动态库
void ImportMethod()
{
    auto _hLibrary = LoadLibraryA("avformat-58.dll");
    if (!_hLibrary)
    {
        printf("error:load %s failed!\n", "avformat-58.dll");
        return;
    }
    dl_avformat_alloc_context=(delegate_avformat_alloc_context)GetProcAddress(_hLibrary, "avformat_alloc_context");
    if (!dl_avformat_alloc_context)                                                                        
    {                                                                                                
        printf("error:%s load %s method failed!\n","avformat-58.dll", "avformat_alloc_context");                                    
    }        
}
//卸载动态库
void UnImport()
{
    if (_hLibrary) {
        FreeLibrary(_hLibrary);
        _hLibrary = nullptr;
    }
}
//使用方法
void UseMethod() {
    auto ic = dl_avformat_alloc_context();
}

2、Linux加载

#include <dlfcn.h>
extern "C"
{
#include "libavformat/avformat.h"
}
//定义方法类型
typedef  AVFormatContext*(*delegate_avformat_alloc_context)(void);
//定义方法指针
delegate_avformat_alloc_context dl_avformat_alloc_context;
void* _hLibrary = nullptr;
//加载动态库
void ImportMethod()
{
    auto _hLibrary = dlopen("libavformat.so", RTLD_LAZY);
    if (!_hLibrary)
    {
        printf("error:load %s failed!\n", "libavformat.so");
        return;
    }
    dl_avformat_alloc_context=(delegate_avformat_alloc_context)dlsym(_hLibrary, "avformat_alloc_context");
    if (!dl_avformat_alloc_context)                                                                        
    {                                                                                                
        printf("error:%s load %s method failed!\n","libavformat.so", "avformat_alloc_context");                                    
    }        
}
//卸载动态库
void UnImport()
{
    if (_hLibrary) {
        dlclose(_hLibrary);
        _hLibrary = nullptr;
    }
}
//使用方法
void UseMethod() {
    auto ic = dl_avformat_alloc_context();
}

3、宏加载

很明显上述流程对于加载一个方法来说流程过于复杂,在遇到库比较多以及方法比较多的情况下,这种方法是很影响开发效率的。但是如果我们对上述流程进行宏包装,事情将会变得简单很多。比如上述引入ffmpeg的avformat_alloc_context方法只需要两行即可:

extern "C"
{
#include "libavformat/avformat.h"
}
//使用宏动态加载方法
DLL_IMPORT("libavformat.so", avformat_alloc_context);
#define avformat_alloc_context DLL_IMPORT_NAME(avformat_alloc_context)
//使用方法
void UseMethod() {
    //与原方法名称一致,直接调用
    auto ic = avformat_alloc_context();
}

二、具体实现

我们通过宏包装上述两个流程即可,同时还需要结合c++11的decltype关键字。

DllImportUtils.h

//
// Created by xin on 2022/6/15.
//
#ifndef DLLIMPORTUTILS_H
#define DLLIMPORTUTILS_H
void* GetDllMethodPtr(const char*dll,const char*method);
#define DLL_IMPORT(dll,method) decltype (method)* dllImport_##method;                            \
namespace {                                                                                         \
    class A##method{                                                                             \
    public: A##method() {                                                                         \
        dllImport_##method = (decltype(dllImport_##method))GetDllMethodPtr(dll, #method);         \
    }                                                                                             \
    };                                                                                             \
    A##method a##method;                                                                         \
}                                                                                                 
#define DLL_IMPORT_NAME(name) dllImport_##name
#endif 

DllImportUtils.cpp

#include"DllImportUtils.h"
#include<map>
#include<string>
#include<stdio.h>
#ifdef _WIN32
#include<Windows.h>
#define ACLoadLibrary(name) LoadLibraryA(name)
#define ACGetProcAdress(dll,name) GetProcAddress((HMODULE)dll,name)
#else
#include <dlfcn.h>
#define ACLoadLibrary(name) dlopen(name,RTLD_LAZY)
#define ACGetProcAdress(dll,name) dlsym(dll,name)
#endif // _Win32
std::map<std::string, void*>* _dllMap = nullptr;
class DllMapDisposer {
public:
    ~DllMapDisposer() {
        if (_dllMap)
            delete _dllMap;
    }
};
static DllMapDisposer _disposer;
void* GetDllMethodPtr(const char* dll, const char* method)
{
    if (!_dllMap)
        _dllMap = new std::map<std::string, void*>;
    auto iter = _dllMap->find(dll);
    void* hm;
    if (iter == _dllMap->end())
    {
        hm = (void*)ACLoadLibrary(dll);
        if (hm)
        {
            (*_dllMap)[dll] = hm;
        }
        else
        {
            printf("warnning:load %s failed!\n", dll);
        }
    }
    else
    {
        hm = iter->second;
    }
    if (hm) {
        auto methodPtr = ACGetProcAdress(hm, method);
        if (!methodPtr)
        {
            printf("error:%s load %s method failed!\n", dll, method);
        }
        return methodPtr;
    }
    return nullptr;
}

三、如何使用

1、引用头文件

引用需要导入方法的头文件

extern "C"
{
//需要导入方法的头文件
#include "libavformat/avformat.h"
}
#include"DllImportUtils.h"

2、添加导入宏

//参数为库的名称和需要导入的方法
DLL_IMPORT("libavformat.so", avformat_alloc_context);
#define avformat_alloc_context DLL_IMPORT_NAME(avformat_alloc_context)

3、直接调用

void UseMethod() {
    //与原方法名称一致,直接调用
    auto ic = avformat_alloc_context();
}

注:当前版本不支持卸载库,程序启动时方法就会被立刻加载。支持跨平台,Windows、Linux都可以使用

总结

以上就是今天要讲的内容,本文讲述的方法很大程度的减少了工作量,而且可以不需要改代码原有逻辑和方法名称,适合需要动态加载不同版本的库或者依赖库的glibc不相同时的场景使用。

原文地址:https://blog.csdn.net/u013113678/article/details/125355481
 
标签: C++ 动态库
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Aurelius vs mORMot vs EntityDAC Delphi 的
    Aurelius vs mORMot vs EntityDAC   Delphi 的 ORM框架:http://www.tmssoftware.com/site/aurelius.asp#product-buy-onlinehttps://synopse.info/fossil/wiki/Synopse+OpenSourcehttps://www.devart.com/entitydac/download.htmlkbmMW  http://www.compo
    02-09
  • 【Ruby】Mac gem的一些坑
    前言自上一次升级MacOS系统后出现jekyll无法构建的问题,当时处理半天。谁知道最近又升级了MacOS,荒废博客多时,今天吝啬写了一篇准备发布,构建报错,问题重新。还是记录下,以防下次升级出问题。问题描述安装jekyll静态博客需要在Ruby环境下运行,于是参照
    02-09
  • iOS oc 调用 swift
    如股票oc要调用swift里面的代码 需要包含固定这个头文件项目名称 LiqunSwiftDemo-Swift.h         #ProjectName#-Swift.h固定的写法swift 目的 是取代oc 但是 不会完全取代 只是前端的替换LiqunSwiftDemo-Swift 点进去 可以看到 所有的swift代码 都产生
    02-09
  • objective-c NSTimer 定时器
    -(void)initTimer{//时间间隔NSTimeInterval timeInterval =3.0 ;//定时器repeats 表示是否需要重复,NO为只重复一次NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(mobileAnimation) userInfo:nil
    02-09
  • Objective-C  日记③ 字符串
    Objective-C 日记③ 字符串
    一、创建字符串、类方法   公式创建NSString  +(id) stringWithFormat:(NSString *) format,……;eg:  NSString *height;  height=[NSString stringWithFormat:@"高度是: %d 长度: %d",10,20];得到的字符串:“高度是: 10 长度: 20” 注意:  省
    02-09
  • Objective-C KVC机制
    Objective-C KVC机制http://blog.csdn.net/omegayy/article/details/7381301全部推翻重写一个版本,这是我在公司内做技术分享的文档总结,对结构、条理做了更清晰的调整。 1.    基本概念MODEL主要是英文文档里面经常出现的一些概念,讲解一下,方便英文
    02-09
  • objective-c 加号 减号 - +
    “加号代表static”是错误的说法,可能跟你那样表达的人其实意思是:“前置加号的方法相当于Java 里面的静态方法”。在Oc中,方法分为类方法和实例方法。前置加号(+)的方法为类方法,这类方法是可以直接用类名来调用的,它的作用主要是创建一个实例。有人把
    02-09
  • Objective-C  日记①
    Objective-C 日记①
    1、Xcode的.m扩展名表示文件含有Object-C代码,C以.c文件,C++以.cpp文件2、头文件声明:C使用:#include,O-C使用#import(当然你也可以使用#include) 3、输出方式:  C:printf("",参数);  O-C:NSLog(@"",参数); 4、布尔类型  C:bool 具有true
    02-09
  • ASP.NET MVC 操作AD 获取域服务器当前用户姓
    #region 根据当前登录域账号 获取AD用户姓名和所在OU目录/// summary/// 根据当前登录域账号 获取AD用户姓名和所在OU目录/// /summary/// param name="searchUser"要搜索的当前用户名/param/// param name="paths"out返回该用户所在OU目录/param/// param nam
    02-09
  • swift和OC - 拆分数组 和 拆分字符串
    1. 拆分数组 /// 根据 数组 截取 指定个数返回 多个数组的集合func splitArray( array: [Date], withSubSize subSize: Int) - [[Date]] {//数组将被拆分成指定长度数组的个数let count = array.count% subSize == 0 ? (array.count/ subSize) : (array.count
    02-08
点击排行