zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Liferay 6.2 改造系列之一:源码编译和服务启动
    安装Maven、Eclipse设置、添加地址JAR
    HTTP状态码查询
    Android Manifest 权限描述大全
    Bootstrap Table 表格参数详解
    Maven项目在Eclipse中调试 Debug
    J2EE中使用jstl报http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar错
    在Eclipse中导入SVN库里的Maven项目
    手机最后一位居然代表你的婚姻爱情
    老九门1-48(全集)
  • 原文地址:https://www.cnblogs.com/1024Planet/p/4425242.html
Copyright © 2011-2022 走看看