0
点赞
收藏
分享

微信扫一扫

dlopen和 dlsym的使用方式

西风白羽 2022-03-26 阅读 74

背景

为了是不同的逻辑解耦,一般会把各个业务封装成动态库,然后主逻辑去调用各个插件。

demo

生产动态库

int add(int a,int b)
{
    return (a + b);
}

int sub(int a, int b)
{
    return (a - b);
}

调用dlopen

#include <dlfcn.h>

void *dlopen(const char *filename, int flag);

char *dlerror(void);

void *dlsym(void *handle, const char *symbol);

int dlclose(void *handle);

dlopen是加载动态链接库,flag可以设置不同的模式(RTLD_LAZY 暂缓决定,等有需要时再解出符号, RTLD_NOW 立即决定,返回前解除所有未决定的符号。), dlopen可以返回动态库的句柄,dlsym是获取动态库中的具体函数名或者变量名。dlopen是关闭动态库。

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
typedef int (*FUNC)(int, int);
int main()
{
    void *handle;
    char *error;
    FUNC func = NULL;

    //打开动态链接库
    handle = dlopen("./libcaculate.so", RTLD_LAZY);
    //获取一个函数
    *(void **) (&func) = dlsym(handle, "add");
    printf("add: %d\n", (*func)(2,7));
    //关闭动态链接库
    dlclose(handle);
}

参考链接

https://www.cnblogs.com/Anker/p/3746802.html

举报

相关推荐

0 条评论