dlopen之另类用法,打开程序本身的符号

好记性不如烂笔头,一直找一直忘,决定还是写下来。

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


*/

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值