最近项目中经常会遇到dlopen和dlsym函数,而且发现使用dlopen时是会对so中的全局对象进行初始化的,所以改了两个小demo,在总结了dlopen相关的几个要点:
- dlopen加载so时会初始化全局变量;
- dlsym可以获取cpp文件中的函数,但必须使用extern "C"声明为C的,否则会出现undefined symbol报错,无法找到符号表;
- dlsym获取类里面的函数,在C++中一般是使用接口的方式,先定义一个统一接口, 类继承它,然后在获取;
一、准备是调用的so
- 准备的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