好记性不如烂笔头,一直找一直忘,决定还是写下来。
dlopen的常规用法是用来打开一个动态库的里面的函数,并在合适的时候执行这个函数。
那么可否使用dlopen打开一个二进制程序本身的函数符号,然后并执行呢?
答案是可以的,只需要在编译的时候加上一个参数即可。
看下面的例子:
#include <stdio.h>
#include <dlfcn.h>
typedef void (*func_p)();
void hello1()
{
printf("this is hello1 function\n");
}
void hello2()
{
printf("this is hello2 function\n");
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("./xxx func_name\n");
return 0;
}
int index = -1;
void *handle = NULL;
func_p f_p = NULL;
// 获取handle,这里一般写一个动态库的名称,现在换成NULL
handle = dlopen(NULL, RTLD_NOW);
if (handle == NULL) {
printf("dlopen error!:%s\n", dlerror());
return -1;
}
// 获取函数func_name
f_p = dlsym(handle, argv[1]);
if (f_p == NULL) {
printf("dlsym error!\n");
dlclose(handle);
return -1;
}
f_p();
// 关闭该handle
dlclose(handle);
return 0;
}
/*
运行结果如下:
[C@root]gcc dlopen_test.c -o dlopen_test -ldl;
[C@root]./dlopen_test hello1
dlsym error!
[C@root]
[C@root]
[C@root]
[C@root]gcc dlopen_test.c -o dlopen_test -ldl -rdynamic
[C@root]./dlopen_test hello1
this is hello1 function
[C@root]./dlopen_test hello2
this is hello2 function
*/