转自:http://cloverprince.iteye.com/blog/481309

现有一个主程序用C语言写成。现在要允许第三方开发人员编写扩展的模块,约定第三方开发的模块必须提供一系列已知名称的函数(如 foo(),bar(),baz())。如果要求第三方的模块必须与主程序的二进制代码分开发布,把dll或so丢在某个文件夹内即可被动态装载并使用,应如何实现?

除了用操作系统提供的接口外,还可以用Glib的简单封装。GLib简单封装了操作系统相关的动态库装载函数,位于GModule中。GModule相当于Library
Handle,而g_module_open, g_module_symbol和g_module_close分别对应dlopen, dlsym和dlclose函数。

接口、动态库同原解 http://cloverprince.iteye.com/blog/481309 ,新的主程序如下:

#include <stdio.h>
#include <stdlib.h> #include <glib.h>
#include <glib/gstdio.h>
#include <gmodule.h> #include "plugin-interface.h" const char * const PLUGINS_PATH = "plugins"; int main(int argc, char** argv) {
GDir *dir;
const gchar *filename; dir = g_dir_open(PLUGINS_PATH,,NULL); while(filename=g_dir_read_name(dir)) {
GModule *module;
char *path; InitModuleFunc init_func;
PluginInterface iface; printf("Openning %s ...\n",filename); path = g_strdup_printf("%s/%s",PLUGINS_PATH,filename); module = g_module_open(path,G_MODULE_BIND_LAZY);
g_module_symbol(module,"init_module",(void**)(&init_func));
init_func(&iface); iface.hello();
iface.greet("wks"); g_module_close(module); g_free(path);
} g_dir_close(dir); return ;
}

编译:
GLib程序的编译可以利用pkg-config辅助设置编译参数

引用

gcc $(pkg-config --cflags --libs glib-2.0 gmodule-2.0) -o main main.c

最新文章

  1. Vue.js&mdash;&mdash;使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用
  2. console对象-转
  3. ZOJ3201 Tree of Tree(树形DP)
  4. java实现httpclient 访问
  5. c#操作文件夹得读写权限
  6. centos内核优化--转至网络
  7. GCD异步加载网络图片
  8. LeetCode 274
  9. USB HID Report Descriptor 报告描述符详解
  10. js 分割循环
  11. 【算法系列学习】HDU 5527 Too Rich贪心
  12. (Android)Wifi-Direct直连
  13. Tomcat输出保存JVM GC日志文件
  14. innodb 关键特性(insert buffer)
  15. day 0308 编码的进阶 文件操作
  16. MyBatis sql语句使用总结
  17. redis 学习笔记1(安装以及控制台命令)
  18. BZOJ2976 : [Poi2002]出圈游戏
  19. 每日英语:Auto Makers Accelerate Efforts to Develop Self-Driving Cars
  20. 10.9zuoye

热门文章

  1. 自己开发的csdn手机客户端
  2. CSS基础(六):浮动深入
  3. Java框架篇---Mybatis 入门
  4. AppCompat Toolbar控件去掉阴影设置高度
  5. Android性能优化之内存篇
  6. [OpenCV] Image Processing - Grayscale Transform
  7. [git]通过commit_id找回文件
  8. android基础----&gt;JSON数据的解析
  9. js-初步了解
  10. UWP开发入门(十五)——在FlipView中通过手势操作图片