linux下实现C语言反射
2015-08-13 15:00
1126 查看
1. 前言
在J***A里实现反射已经家常便饭了,而在C语言程序里还从未实现过,遇到了正好研究下,这里只贴下代码,这段代码是从网上摘来了,只不过进行了完善,保证可以正确编译。
2.代码
[code]#include <stdio.h> #include <libelf.h> #include <gelf.h> #include <sys/stat.h> #include <fcntl.h> void test(int i) { printf(" call test with i:%d\n", i); } int main(int argc, char** argv) { Elf *elf = NULL; Elf_Scn *scn = NULL; GElf_Shdr shdr; Elf_Data *data = NULL; int fd, ii, count; void (*test_func)(int); elf_version(EV_CURRENT); fd = open(argv[0], O_RDONLY); elf = elf_begin(fd, ELF_C_READ, NULL); while((scn = elf_nextscn(elf, scn)) != NULL) { gelf_getshdr(scn, &shdr); if(shdr.sh_type == SHT_SYMTAB) { break; } } data = elf_getdata(scn, NULL); count = shdr.sh_size / shdr.sh_entsize; for(ii = 0; ii < count; ++ii) { GElf_Sym sym; gelf_getsym(data, ii, &sym); if(strcmp("test", elf_strptr(elf, shdr.sh_link, sym.st_name))) continue; test_func = (void (*)(int))(sym.st_value); test_func(255); break; } elf_end(elf); close(fd); return 0; }
3. 编译运行
3.1 编译
[code]gcc test.c -o test
3.2 运行
[code]./test
3.3 输出
[code] call test with i:255
4. 小结
ACE也使用了此方法,此方法用来做些高扩展性的程序还是蛮方便的,为我们打开一个很好的思路。相关文章推荐
- 深入理解SELinux SEAndroid(结局)
- 【system】 linux 服务器之间拷贝文件
- 深入理解SELinux SEAndroid 第二部分
- 深入理解SELinux SEAndroid
- Linux之centos6.5搭建DNS分离解析
- Linux用户空间与内核交互——ioclt
- Linux中查看CPU信息
- 查看 SELinux状态及关闭SELinux
- centos6.6 从源码编译安装mysql5.7.5
- Linux中环境变量文件及配置
- CentOS下在大文件中查找某个字符串
- Linux学习-14-学习磁盘配额(Quota)
- Linux学习-13-学习ACL的使用-2
- Linux下安装MySQL数据库相关
- 配置SELINUX
- Linux入门基本指令
- linux 创建swap分区
- 2-3-RHEL6.3搭建NTP 服务器案例分析与总结(RedHat Enterprise Linux Server6.3)@树袋飘零
- Linux下Jmeter后台分布式执行
- Linux chmod +755和chmod +777 各是什么意思呢?