zoukankan      html  css  js  c++  java
  • so加载的构造函数和析构函数

    http://blog.csdn.net/linuw/article/details/6048307

    __attribute__ ((constructor))指定的函数在共享库loading的时候调用,__attribute__ ((destructor))指定的函数在共享库unloading的时候调用。

    so代码:

    #include <stdio.h>
    
    __attribute__ ((constructor)) static void so_init(void);
    __attribute__ ((destructor)) static void so_deinit(void);
    
    void so_init(void)
    {
        printf("call so init.
    ");
    }
    
    void so_deinit(void)
    {
        printf("call so deinit.
    ");
    }
    
    void test1()
    {
        printf("call test1.
    ");
    }
    
    void test2()
    {
        printf("call test2.
    ");
    }
    
    void test3()
    {
        printf("call test3.
    ");
    }
    
    
    /*
    gcc -fPIC -c so_lib.c   
    gcc -shared -o libxxx.so so_lib.o
    */

    app代码:

    #include <stdlib.h>
    #include <stdio.h>
    #include <dlfcn.h> /* dlopen, dlsym, dlclose */
    
    void test1();
    void test2();
    void test3();
    
    int main(int argc, char **argv)
    {
        test1();
        test2();
        test3();
    
        /* below only for testing dynamic linking loader */
        void *handle;
        void (*test)();
        char *error;
    
        handle = dlopen ("./libxxx.so", RTLD_LAZY);
        if (!handle) {
            fputs(dlerror(), stderr);
            exit(1);
        }
    
        test = dlsym(handle, "test2");
        if ((error = dlerror()) != NULL)  {
            fputs(error, stderr);
            exit(1);
        }
    
        (*test)();
        dlclose(handle);
    
        return 0;
    }
    
    /*
    gcc so_app.c -ldl -L./ -lxxx 
      
    export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH && ./a.out 
    */
  • 相关阅读:
    Tips for Hoops 3D & ACIS
    把书读薄TICPP(2)
    Software Toolbox EasyOPC简介
    Wonderware InSQL and Incurity安装心得
    Linux root password reset
    SQL Server 2005 的搞笑
    SVG 简介
    M0n0wall 是什么?
    Solaris 上调试系统 hang 的总结
    DDNS简介
  • 原文地址:https://www.cnblogs.com/soul-stone/p/6690767.html
Copyright © 2011-2022 走看看