c/c++ 直接使用动态库 dlopen

把各个版本编译成动态库,××.so ,提供统一的接口进行调用。这里使用的工具是dlxx系列函数

  • dlopen  void *dlopen(const char *filename, int flag);    装载动态库
  • dlclose int dlclose(void *handle);
  • dlerror char *dlerror(void); 返回可读字符串
  • dladdr
  • dlsym void *dlsym(void *handle, const char *symbol);
  • dlvsym
例子
 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <dlfcn.h>
  4. //gcc flag
  5. // gcc t_dlopen.c -ldl
  6. int
  7. main(int argc, char **argv)
  8. {
  9. void *handle;
  10. double (*cosine)(double);
  11. char *error;
  12. handle = dlopen("libm.so", RTLD_LAZY);
  13. if (!handle) {
  14. fprintf(stderr, "%s\n", dlerror());
  15. exit(EXIT_FAILURE);
  16. }
  17. dlerror(); /* Clear any existing error */
  18. /* Writing: cosine = (double (*)(double)) dlsym(handle, "cos");
  19. would seem more natural, but the C99 standard leaves
  20. casting from "void *" to a function pointer undefined.
  21. The assignment used below is the POSIX.1-2003 (Technical
  22. Corrigendum 1) workaround; see the Rationale for the
  23. POSIX specification of dlsym(). */
  24. *(void **) (&cosine) = dlsym(handle, "cos");
  25. if ((error = dlerror()) != NULL) {
  26. fprintf(stderr, "%s\n", error);
  27. exit(EXIT_FAILURE);
  28. }
  29. printf("%f\n", (*cosine)(0.0));
  30. dlclose(handle);
  31. exit(EXIT_SUCCESS);
  32. }
编译使用库 libdl
gcc t_dlopen.c -ldl
输出
  1. 1.000000
运用技巧,写个基本框架,很容易就能实现某些公司鼓吹的dll编程
 
 
参考文章
===========================

Internet 浏览器用户非常熟悉插件的概念。从 Web
上下载插件,通常这些插件为浏览器的音频、视频以及特殊效果提供增强支持。一般来讲,在不更改原有应用程序的情况下,插件为现有应用程序提供新功能。

DLL
是程序函数,它们在设计和构建应用程序时为该程序所知。设计应用程序的主程序时使用程序框架或底板,这些程序框架或底板在运行时选择性地装入所需的
dll,这些 dll
位于磁盘上同主程序分离的一些文件中。这一打包和动态装入提供了灵活的升级、维护、以及许可策略。

随 Linux 一起交付的还有几千条命令和应用程序,它们至少都需要 libc
库函数。如果 libc
函数与每一个应用程序都打包在一起,那么磁盘上将会出现几千个相同函数的副本。Linux
构建这些应用程序,以使用通常所需的系统库的单个系统级副本,而不浪费磁盘空间。Linux
甚至做得更好,每个需要公共系统库函数的进程使用单个的系统级内的副本,一次性将该副本装入到内存并为各进程所共享。

在 Linux 中,插件和 dll
以动态库形式实现。本文的余下部分是在应用程序运行之后使用动态库更改该应用程序的示例。

Linux 动态链接

Linux
中的应用程序以以下两种方式之一链接到外部函数:要么在构建时与静态库(

lib*.a )
静态地链接,并且将库代码包含在该应用程序的可执行文件里;要么在运行时与共享库(

lib*.so )
动态地链接。通过动态链接装入器,将动态库映射进应用程序的可执行内存中。在启动应用程序之前,动态链接装入器将所需的共享目标库映射到应用程序的内存,或者使用系统共享的目标并为应用程序解析所需的外部引用。现在应用程序就可以运行了。

作为示例,下面有一个演示 Linux
中对动态链接库的缺省使用的小程序:

  1. main()
  2. {
  3. printf("Hello world
  4. ");
  5. }

当使用 gcc 编译 hello.c 时,就创建了一个名为
a.out
的可执行文件。通过使用 Linux 命令
ldd
a.out (该命令打印出共享库的相互依赖性),可以看出所需的共享库是:

libc.so.6 => /lib/libc.so.6 (0x4001d000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

使用相同的动态链接装入器在应用程序运行之后将 dll
映射进应用程序的内存。通过使用 Linux
动态装入器例程,应用程序控制装入哪一个动态库以及调用库中的哪一个函数,以执行装入和链接以及返回所需入口点的地址。

Linux dll 函数

Linux 提供 4 个库函数(
dlopen ,
dlerror ,
dlsym 和
dlclose ),一个 include
文件(
dlfcn.h )以及两个共享库(静态库
libdl.a 和动态库
libdl.so ),以支持动态链接装入器。这些库函数是:

  • dlopen
    将共享目标文件打开并且映射到内存中,并且返回句柄
  • dlsym返回一个指向被请求入口点的指针
  • dlerror 返回 NULL 或者一个指向描述最近错误的 ASCII
    字符串的指针
  • dlclose关闭句柄并且取消共享目标文件的映射

动态链接装入器例程 dlopen
需要在文件系统中查找共享目标文件以打开文件并创建句柄。有 4
种方式用以指定文件的位置:

  • dlopen call 中的绝对文件路径
  • 在 LD_LIBRARY_PATH 环境变量中指定的目录中
  • 在 /etc/ld.so.cache 中指定的库列表之中
  • 先在 /usr/lib 之中,然后在 /lib 之中

dll 示例:小的 C 程序和 dlTest

动态链接装入器示例程序是一个小的 C 程序,该程序被设计用来练习 dl
例程。该程序基于每个人都编写过的一个 C 程序,它将“Hello
World”打印到控制台上。最初打印的消息是“HeLlO
WoRlD”。该测试程序链接到再次打印该消息的两个函数上:第一次都用大写字符,第二次都用小写字符。

以下是该程序的概要:

  1. 定义 dll include 文件
    dlfcn.h 和所需的变量。
    至少需要这些变量:

    • 到共享库文件的句柄
    • 指向被映射函数入口点的指针
    • 指向错误字符串的指针
  2. 打印初始消息,“HeLlO WoRlD”。
  3. 使用绝对路径“/home/dlTest/UPPERCASE.so”和选项
    RTLD_LAZY,
    dlopen 打开 UPPERCASE dll
    的共享目标文件并返回句柄。

    • 选项 RTLD_LAZY 推迟解析 dll 的外部引用,直到 dll 被执行。
    • 选项 RTLD_NOW 在
      dlopen
      返回之前解析所有的外部引用。
  4. dlsym 返回入口点 printUPPERCASE 的地址。
  5. 调用 printUPPERCASE 并且打印修改过的消息“HELLO WORLD”。
  6. dlclose 关闭到 UPPERCASE.so
    的句柄,并且从内存中取消 dll 映射。
  7. dlopen 使用基于环境变量 LD_LIBRARY_PATH
    的相对路径查找共享目标路径,来打开 lowercase dll 的共享目标文件
    lowercase.so,并且返回句柄。
  8. dlsym 返回入口点 printLowercase 的地址。
  9. 调用 printLowercase 并且打印修改过的信息“hello world”。
  10. dlclose 关闭到 lowercase.so
    的句柄,并且从内存中取消 dll 映射。

注意,每次调用
dlopen 、
dlsym 或
dlclose 之后,调用
dlerror
以获取最后的错误信息,并且打印该错误信息字符串。以下是 dlTest
的测试运行:

dlTest 2-Original message
HeLlO WoRlD
dlTest 3-Open Library with absolute path return-(null)-
dlTest 4-Find symbol printUPPERCASE return-(null)-
HELLO WORLD
dlTest 5-printUPPERCASE return-(null)-
dlTest 6-Close handle return-(null)-
dlTest 7-Open Library with relative path return-(null)-
dlTest 8-Find symbol printLowercase return-(null)-
hello world
dlTest 9-printLowercase return-(null)-
dlTest 10-Close handle return-(null)-

完整的 dlTest.c、UPPERCASE.c 和 lowercase.c
源代码清单在本文后面的
清单里。

构建 dlTest

启用运行时动态链接需要三步:

  1. 将 dll 编译为位置无关代码
  2. 创建 dll 共享目标文件
  3. 编译主程序并同 dl 库相链接

编译 UPPERCASE.c 和 lowercase.c 的 gcc 命令包含 -fpic 选项。选项
-fpic 和 -fPIC
导致生成的代码是位置无关的,重建共享目标库需要位置无关。-fPIC
选项产生位置无关的代码,这类代码支持大偏移。用于 UPPERCASE.o 和
lowercase.o 的第二个 gcc 命令,带有 -shared
选项,该选项产生适合于动态链接的共享目标文件 a*.so。

用于编译和执行 dltest 的 ksh 脚本如下:

  1. #!/bin/ksh
  2. # Build shared library
  3. #
  4. #set -x
  5. clear
  6. #
  7. # Shared library for dlopen absolute path test
  8. #
  9. if [ -f UPPERCASE.o ]; then rm UPPERCASE.o
  10. fi
  11. gcc -c -fpic UPPERCASE.c
  12. if [ -f UPPERCASE.so ]; then rm UPPERCASE.so
  13. fi
  14. gcc -shared -lc -o UPPERCASE.so UPPERCASE.o
  15. #
  16. # Shared library for dlopen relative path test
  17. #
  18. export LD_LIBRARY_PATH=`pwd`
  19. if [ -f lowercase.o ]; then rm lowercase.o
  20. fi
  21. gcc -c -fpic lowercase.c
  22. if [ -f lowercase.so ]; then rm lowercase.so
  23. fi
  24. gcc -shared -lc -o lowercase.so lowercase.o
  25. #
  26. # Rebuild test program
  27. #
  28. if [ -f dlTest ]; then rm dlTest
  29. fi
  30. gcc -o dlTest dlTest.c -ldl
  31. echo Current LD_LIBRARY_PATH=$LD_LIBRARY_PATH
  32. dlTest

结束语

创建能在运行时被动态链接到 Linux
系统上的应用程序的共享目标代码是一项非常简单的练习。应用程序通过使用对动态链接装入器的
dlopen、dlsym 和 dlclose
函数调用来获取对共享目标文件的访问。dlerror
以字符串的形式返回任何错误,这些错误信息字符串描述 dl
函数碰到的最后一个错误。在运行时,主应用程序使用绝对路径或相对于
LD_LIBRARY_PATH 的相对路径找到共享目标库,并且请求所需的 dll
入口点的地址。当需要时,也可对 dll
进行间接函数调用,最后,关闭到共享目标文件的句柄,并且从内存中取消该目标文件映射,使之不可用。

使用附加选项 -fpic 或 -fPIC
编译共享目标代码,以产生位置无关的代码,使用 -shared
选项将目标代码放进共享目标库中。

Linux
中的共享目标代码库和动态链接装入器向应用程序提供了额外的功能。减少了磁盘上和内存里的可执行文件的大小。可以在需要时,装入可选的应用程序功能,可以在无须重新构建整个应用程序的情况下修正缺陷,并且应用程序可以包含第三方的插件。

清单(应用程序和 dll)

dlTest.c:

  1. /*************************************************************/
  2. /* Test Linux Dynamic Function Loading */
  3. /* */
  4. /* void *dlopen(const char *filename, int flag) */
  5. /* Opens dynamic library and return handle */
  6. /* */
  7. /* const char *dlerror(void) */
  8. /* Returns string describing the last error. */
  9. /* */
  10. /* void *dlsym(void *handle, char *symbol) */
  11. /* Return pointer to symbol's load point. */
  12. /* If symbol is undefined, NULL is returned. */
  13. /* */
  14. /* int dlclose (void *handle) */
  15. /* Close the dynamic library handle. */
  16. /* */
  17. /* */
  18. /* */
  19. /*************************************************************/
  20. #include<stdio.h>
  21. #include <stdlib.h>
  22. /* */
  23. /* 1-dll include file and variables */
  24. /* */
  25. #include <dlfcn.h>
  26. void *FunctionLib; /* Handle to shared lib file */
  27. int (*Function)(); /* Pointer to loaded routine */
  28. const char *dlError; /* Pointer to error string */
  29. main( argc, argv )
  30. {
  31. int rc; /* return codes */
  32. char HelloMessage[] = "HeLlO WoRlD\n";
  33. /* */
  34. /* 2-print the original message */
  35. /* */
  36. printf(" dlTest 2-Original message \n");
  37. printf("%s", HelloMessage);
  38. /* */
  39. /* 3-Open Dynamic Loadable Libary with absolute path */
  40. /* */
  41. FunctionLib = dlopen("/home/dlTest/UPPERCASE.so",RTLD_LAZY);
  42. dlError = dlerror();
  43. printf(" dlTest 3-Open Library with absolute path return-%s- \n", dlError);
  44. if( dlError ) exit(1);
  45. /* */
  46. /* 4-Find the first loaded function */
  47. /* */
  48. Function = dlsym( FunctionLib, "printUPPERCASE");
  49. dlError = dlerror();
  50. printf(" dlTest 4-Find symbol printUPPERCASE return-%s- \n", dlError);
  51. if( dlError ) exit(1);
  52. /* */
  53. /* 5-Execute the first loaded function */
  54. /* */
  55. rc = (*Function)( HelloMessage );
  56. printf(" dlTest 5-printUPPERCASE return-%s- \n", dlError);
  57. /* */
  58. /* 6-Close the shared library handle */
  59. /* Note: after the dlclose, "printUPPERCASE" is not loaded */
  60. /* */
  61. rc = dlclose(FunctionLib);
  62. dlError = dlerror();
  63. printf(" dlTest 6-Close handle return-%s-\n",dlError);
  64. if( rc ) exit(1);
  65. /* */
  66. /* 7-Open Dynamic Loadable Libary using LD_LIBRARY path */
  67. /* */
  68. FunctionLib = dlopen("lowercase.so",RTLD_LAZY);
  69. dlError = dlerror();
  70. printf(" dlTest 7-Open Library with relative path return-%s- \n", dlError);
  71. if( dlError ) exit(1);
  72. /* */
  73. /* 8-Find the second loaded function */
  74. /* */
  75. Function = dlsym( FunctionLib, "printLowercase");
  76. dlError = dlerror();
  77. printf(" dlTest 8-Find symbol printLowercase return-%s- \n", dlError);
  78. if( dlError ) exit(1);
  79. /* */
  80. /* 8-execute the second loaded function */
  81. /* */
  82. rc = (*Function)( HelloMessage );
  83. printf(" dlTest 9-printLowercase return-%s- \n", dlError);
  84. /* */
  85. /* 10-Close the shared library handle */
  86. /* */
  87. rc = dlclose(FunctionLib);
  88. dlError = dlerror();
  89. printf(" dlTest 10-Close handle return-%s-\n",dlError);
  90. if( rc ) exit(1);
  91. return(0);
  92. }

UPPERCASE.c:

  1. /************************************************/
  2. /* Function to print input string as UPPER case. */
  3. /* Returns 1. */
  4. /*********************************************** */
  5. int printUPPERCASE ( inLine )
  6. char inLine[];
  7. {
  8. char UPstring[256];
  9. char *inptr, *outptr;
  10. inptr = inLine;
  11. outptr = UPstring;
  12. while ( *inptr != '\0' )
  13. *outptr++ = toupper(*inptr++);
  14. *outptr++ = '\0';
  15. printf(UPstring);
  16. return(1);
  17. }

lowercase.c

  1. /********************************************/
  2. /* Function to print input string as lower case. */
  3. /* Returns 2. */
  4. /******************************************* */
  5. int printLowercase( inLine )
  6. char inLine[];
  7. {
  8. char lowstring[256];
  9. char *inptr, *outptr;
  10. inptr = inLine;
  11. outptr = lowstring;
  12. while ( *inptr != '' )
  13. *outptr++ = tolower(*inptr++);
  14. *outptr++ = '';
  15. printf(lowstring);
  16. return(2);
  17. }
 
===========================
 
参考
  1. man dlopen
  2. 为 Linux 应用程序编写 DLL        http://www.ibm.com/developerworks/cn/linux/sdk/dll/index.html

c/c++ 直接使用动态库 dlopen的更多相关文章

  1. C 高级编程3 静态库与动态库

    http://blog.csdn.net/Lux_Veritas/article/details/11934083http://www.cnblogs.com/catch/p/3857964.html ...

  2. Linux 动态库的编译和使用

    1. 动态链接库简介 动态库又叫动态链接库,是程序运行的时候加载的库,当动态链接库正确安装后,所有的程序都可以使用动态库来运行程序.动态库是目标文件的集合,目标文件在动态库中的组织方式是按特殊的方式组 ...

  3. Linux下c函数dlopen实现加载动态库so文件代码举例

    dlopen()是一个强大的库函数.该函数将打开一个新库,并把它装入内存.该函数主要用来加载库中的符号,这些符号在编译的时候是不知道的.这种机制使得在系统中添加或者删除一个模块时,都不需要重新编译了. ...

  4. linux c编程调用系统的动态库时,要使用dlopen等函数吗?

    同问 linux c编程调用系统的动态库时,要使用dlopen等函数吗? 2012-11-27 21:55 提问者: hnwlxyzhl 我来帮他解答 满意回答 2012-12-07 09:08 li ...

  5. 使用dlopen加载动态库

    目录 概述 接口 C CMakeLists.txt src/main.c src/add.c ./dlopen_test C++ CMakeLists.txt src/main.cpp src/add ...

  6. Android 5.0 到 Android 6.0 + 的深坑之一 之 .so 动态库的适配

    (原创:http://www.cnblogs.com/linguanh) 目录: 前序 一,问题描述 二,为何会如此"无情"? 三,目前存在该问题的知名SDK 四,解决方案,1 对 ...

  7. C++ 系列:静态库与动态库

    转载自http://www.cnblogs.com/skynet/p/3372855.html 这次分享的宗旨是——让大家学会创建与使用静态库.动态库,知道静态库与动态库的区别,知道使用的时候如何选择 ...

  8. C++静态库与动态库

    C++静态库与动态库 这次分享的宗旨是--让大家学会创建与使用静态库.动态库,知道静态库与动态库的区别,知道使用的时候如何选择.这里不深入介绍静态库.动态库的底层格式,内存布局等,有兴趣的同学,推荐一 ...

  9. Linux动态库的编译与使用 转载

    http://hi.baidu.com/linuxlife/blog/item/0d3e302ae2384d3a5343c1b1.html Linux下的动态库以.so为后缀,我也是初次在Linux下 ...

随机推荐

  1. 我对国内两大购书站点的感受(dearbook和china-pub)

    我在china-pub和dearbook都是老用户了(china-pub五星,dearbook钻石VIP).说一下近来我对两个站点的感觉. 1. Dearbook和当当合作以后送货速度比china-p ...

  2. poj 3368 Frequent values(段树)

    Frequent values Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 13516   Accepted: 4971 ...

  3. libevent: linux安装libevent

    http://libevent.org/上下载最新的libevent, 如 libevent-2.0.22-stable.tar.gz. 然后解压,按照README里面的步骤安装.

  4. 闲扯 Javascript 02 全选、不选、反选

    <body> <input id="btn1" type="button" value="全选" /><br& ...

  5. vim添加删除多行注释

    CTRL+V进入可视化模式 移动光标上移或者下移,选中多行的开头 选择完毕后,按大写的的I键,此时下方会提示进入“insert”模式,输入你要插入的注释符 最后按ESC键,你就会发现多行代码已经被注释 ...

  6. Creating Spatial Indexes(mysql 创建空间索引 The used table type doesn't support SPATIAL indexes)

    For MyISAM tables, MySQL can create spatial indexes using syntax similar to that for creating regula ...

  7. ORA-01093: ALTER DATABASE CLOSE only permitted with no sessions connected解决方法

    在进行物理主备库角色转换的时候遇到ORA-01093错误 SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY; ALTER ...

  8. 半透明panel

    用API  SetLayeredWindowAttributes

  9. Swing Dance!摇摆舞!小组

    Swing Dance!摇摆舞!小组 Swing Dance!摇摆舞

  10. linux命令:du,看文件大小

    du -s698 . (698字节)From <http://jingyan.baidu.com/article/a17d52855c10bf8098c8f2c9.html>