您的位置:首页 > 运维架构 > Linux

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也使用了此方法,此方法用来做些高扩展性的程序还是蛮方便的,为我们打开一个很好的思路。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: