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 
    */
  • 相关阅读:
    Mybatis plus 配置
    logback配置
    iview-ui-project-4.0 安装与配置
    Linux系统下Redis安装与配置
    Java中枚举的用法
    Mysql 查询所有课程的成绩第2名到第3名的学生信息及该课程成绩
    java 基础知识一 初识java
    docker 查看 挂载目录
    sqlserver统计所有表及表中记录数
    centos7配置禁用ipv6
  • 原文地址:https://www.cnblogs.com/soul-stone/p/6690767.html
Copyright © 2011-2022 走看看