V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
chaker
V2EX  ›  程序员

如何修改shared library中的某个变量值?

  •  
  •   chaker · 2013-06-28 12:34:04 +08:00 · 2999 次点击
    这是一个创建于 3947 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如这样一个例子:
    int count(){
    int num = 9;
    int result = 0;
    for ( int i = 0; i < num; i++ ){
    result ++;
    }
    return result;
    }
    封装成lib.so文件。

    希望在动态加载的时候
    void *handler = dlopen("lib.so", RTLD_LAZY);
    能修改num的值,每次调用都循环不同的次数。

    如何在lib和主程序里设计接口?不能定义成 int count( int num ) 的形式。
    如果更复杂点,每次需要修改的参数类型和个数都是变化的又该怎么办?
    不能include lib的header文件。

    谢谢。
    13 条回复    1970-01-01 08:00:00 +08:00
    nybux
        1
    nybux  
       2013-06-28 13:30:25 +08:00
    配置文件?
    chaker
        2
    chaker  
    OP
       2013-06-28 13:42:31 +08:00
    @nybux 是一种方法,但是太麻烦了,如果so能直接从主程序里读取数据最好了
    chaker
        3
    chaker  
    OP
       2013-06-28 16:23:58 +08:00
    或者动态库里怎么使用主函数里的变量?
    nybux
        4
    nybux  
       2013-06-28 16:57:23 +08:00
    编译时加上-fPIC就可以了
    nybux
        5
    nybux  
       2013-06-28 16:59:37 +08:00
    -> % cat b.c
    #include <stdio.h>
    int i = 19;
    int main() {
    foo();
    }
    -> % cat a.c
    #include <stdio.h>
    extern int i;
    int foo() {
    printf("%d\n", i);
    }
    -> % gcc -shared -fPIC a.c -o a.so
    -> % gcc b.c a.so
    -> % LD_LIBRARY_PATH=. ./a.out
    19
    jiych
        6
    jiych  
       2013-06-28 17:05:03 +08:00
    gdb算吗?
    chaker
        7
    chaker  
    OP
       2013-06-28 17:11:55 +08:00
    @nybux 但是这样就不是动态加载了啊,需要把so文件加到主函数里了
    chaker
        8
    chaker  
    OP
       2013-06-28 17:12:54 +08:00
    @jiych 这个。。。当然不能算。。。总不能让用户用gdb运行他的程序吧。。。
    chaker
        9
    chaker  
    OP
       2013-06-28 17:17:35 +08:00
    @nybux 或者可以通过传递一个类实现吗
    nybux
        10
    nybux  
       2013-06-28 17:51:08 +08:00
    这样还是动态加载的,如果a.so不存在的话
    -> % ./a.out
    ./a.out: error while loading shared libraries: a.so: cannot open shared object file: No such file or directory
    传递类比前面体的所有方案都麻烦,可以传递结构,也就是一个void*啦
    chaker
        11
    chaker  
    OP
       2013-06-28 19:29:29 +08:00
    @nybux 确实是这样,但是我用的时候是先把主函数写好编译完,然后就不能动了。so文件以后随时写随时加载
    nybux
        12
    nybux  
       2013-06-28 22:36:04 +08:00
    可以先生成一个空实现的so文件,用于给主程序编译
    以后再慢慢修改so文件,重新生成so文件,不需要再编译主程序。
    chaker
        13
    chaker  
    OP
       2013-06-29 19:19:10 +08:00
    @nybux 我用全局变量解决了,在主函数里直接dlsym修改so里的全局变量,谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4642 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:00 · PVG 12:00 · LAX 21:00 · JFK 00:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.