• C语言下动态库相互调用


    前段时间需要完成多个模块业务,而这些模块的接口都是一样的,于是为了方便管理就把每个模块都根据接口封装成了SO库,这里就留下SO库调用样例

    SO库源文件代码:

    1 //TestSo.c
    2 #include <stdio.h>
    3 
    4 int CommonInterface(char* str, unsigned int strLen)
    5 {
    6     //deal with ...
    7     printf("%s, %d
    ", str, strLen);
    8     return 1;
    9 }

    编译命令:

    gcc -shared -o TestSo.so TestSo.c
     
    使用库代码:
     1 //Main.c
     2 #include <stdio.h>
     3 #include <dlfcn.h>
     4 
     5 typedef int (*CommonInterface_Func)(char* str, unsigned int strLen);
     6 
     7 #define TEST_SO_FILE "/root/test/libtestSo.so"
     8 void* soHandle = NULL;
     9 
    10 /* get dynamic library function address, returns 1 success, otherwise fail. */
    11 int getCommonInterfaceFuncAddr(CommonInterface_Func* funcAddr)
    12 {
    13     // laod dynamic library.
    14     soHandle = dlopen(TEST_SO_FILE, RTLD_LAZY);
    15     if ( soHandle == NULL )
    16     {
    17         printf("dlopen,(%s)", dlerror());
    18         return 0;
    19     }    
    20     // get func addr
    21     *funcAddr = (CommonInterface_Func)dlsym(soHandle, "CommonInterface");
    22     if ( *funcAddr == NULL )
    23     {
    24         printf("dlsym,(%s)", dlerror());
    25         dlclose(m_soHandle);
    26         return 0;
    27     }
    28     return 1;
    29 }
    30 
    31 int main(int argc, char* argv[])
    32 {
    33     char* str = "hello so.";
    34     CommonInterface_Func funcAddr = NULL;
    35     int result = getCommonInterfaceFuncAddr(&funcAddr);
    36 
    37     if (result != 1)
    38     {
    39         printf("get func address fail.
    ");
    40         return 0;
    41     }
    42     printf("get func address success.
    ");
    43     result = funcAddr(str, strlen(str));
    44     printf("exec func result : %d
    ", result);
    45     
    46     return 1;
    47 }

    编译命令:

     gcc -o Main_exec Main.c -ldl

     执行:./Main_exec

    参考链接:http://www.cnblogs.com/leaven/archive/2010/06/11/1756294.html

  • 相关阅读:
    函数语法:Js之on和addEventListener的使用与不同
    练习:javascript弹出框及地址选择功能,可拖拽
    jQuery.extend 函数使用
    计算输入时间如“ 2018-12-12” 的 00:00:00距离现在的时间间隔
    JS获取当前时间戳的方法
    常规正则表达式练习
    登录表单验证简单实现
    简单计算器
    MySQL 单表查询
    C++读写文件
  • 原文地址:https://www.cnblogs.com/1024Planet/p/4425242.html
Copyright © 2020-2023  润新知