一、dlopen、dlsym我所理解的是通过dlopen可以动态加载一个so,通过dlsym可以获得该so中某接口的地址,从而实现使用该so中接口的功能。
二、代码如下:
mylib.cpp
#include <stdio.h>
#include <stdlib.h>
/*
* c++编译后的文件会把函数名改名(为了实现重载功能)
* 用extern "C"声明后,就会使用c的方式进行编译,编译后的文件中仍然是定义的函数名
*/
extern "C"
{
void feng(void)
{
printf("111111\n");
}
}
g++ -shared -fPIC -o mylib.so mylib.cpp
dlopen_test.cpp
#include <stdlib.h>
#include <dlfcn.h>
#include <stdio.h>
void(*pMytest)(void );
int main(void) {
void *handle = NULL;
char *myso = "./mylib.so";
dlerror();
if((handle = dlopen(myso, RTLD_NOW)) == NULL) {
printf("dlopen - %sn", dlerror());
exit(-1);
}
printf("success\n");
pMytest = (void(*)(void))dlsym(handle, "feng");
printf("error:%s\n", dlerror());
printf("success end\n");
pMytest();
return 0;
}
g++ -o dlopen_test dlopen_test.cpp -ldl -rdynamic
运行可得到:1111111
注意so中的函数要用到extern "C",否则运行./dlopen_test会报undefined symbol dlsym的错误,因为c++编译后的文件会把函数名改名(为了实现重载功能),用extern "C"声明后,就会使用c的方式进行编译,编译后的文件中仍然是定义的函数名,可以通过nm来看so中函数的名称。
如果不加extern "C“

加上后: