dlopenC++动态库初探

最近项目中经常会遇到dlopen和dlsym函数,而且发现使用dlopen时是会对so中的全局对象进行初始化的,所以改了两个小demo,在总结了dlopen相关的几个要点:

  1. dlopen加载so时会初始化全局变量;
  2. dlsym可以获取cpp文件中的函数,但必须使用extern "C"声明为C的,否则会出现undefined symbol报错,无法找到符号表;
  3. dlsym获取类里面的函数,在C++中一般是使用接口的方式,先定义一个统一接口, 类继承它,然后在获取;

一、准备是调用的so

  1. 准备的so其中包含一个类:
//mytest.h
#include <stdio.h>
#include <iostream>
using namespace std;

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

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

    int mul(int a, int b)
    {
        return (a * b);
    }

    int mdiv(int a, int b)
    {
        return (a / b);
    }
}

class mytest
{
public:
    // static mytest    s_mytest;
    // static int num;
    // int mdiv(int a, int b);
    // int mul(int a, int b);
    // int sub(int a, int b);
    // int add(int a,int b);
    mytest(/* args */);
    ~mytest();
};

对应类的实现

//mytest.cpp
#include "mytest.h"

//定义的是静态全局变量,那么在加载so时只会有一个实例
// mytest    mytest::s_mytest;
//非静态全局变量,加载时可能会有多个实例
mytest    s_mytest;

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

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

// int mytest::mul(int a, int b)
// {
//     return (a * b);
// }

// int mytest::mdiv(int a, int b)
// {
//     return (a / b);
// }



mytest::mytest(/* args */)
{
    static int num = 0;
    num++;
    cout<<"init num:"<<num<<endl;
    // num=1;
    // cout<<"mytest::num:"<<num<<endl;
}

mytest::~mytest()
{
    cout<<"relese"<<endl;
}

编译成so:

g++ -fPIC -shared mytest.cpp mytest.h -o libmytest.so

二、调用so的main函数

#include <dlfcn.h>
#include <iostream>
using namespace std;

//动态链接库路径
#define LIB_CACULATE_PATH "./libmytest.so"

//函数指针
typedef int (*CAC_FUNC)(int, int);

int main()
{
    void *handle;
    char *error;
    CAC_FUNC cac_func = NULL;

    //打开动态链接库
    handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY);
    if (!handle) {
    fprintf(stderr, "%s\n", dlerror());
    exit(EXIT_FAILURE);
    }

    //清除之前存在的错误
    dlerror();

    //获取一个函数
    *(void **) (&cac_func) = dlsym(handle, "add");
    if ((error = dlerror()) != NULL)  {
    fprintf(stderr, "%s\n", error);
    exit(EXIT_FAILURE);
    }
    printf("add: %d\n", (*cac_func)(2,7));

    cac_func = (CAC_FUNC)dlsym(handle, "sub");
    printf("sub: %d\n", cac_func(9,2));

    cac_func = (CAC_FUNC)dlsym(handle, "mul");
    printf("mul: %d\n", cac_func(3,2));

    cac_func = (CAC_FUNC)dlsym(handle, "mdiv");
    printf("div: %d\n", cac_func(8,2));

    //关闭动态链接库
    dlclose(handle);
    exit(EXIT_SUCCESS);
}

编译main函数:

g++ -rdynamic -o main main.cpp -ldl

输出的结果:

./main 
init num:1
add: 9
sub: 7
mul: 6
div: 4
relese

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值