插件问题回答第1题 另解

问题贴:[url]http://cloverprince.iteye.com/blog/481307[/url]

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


回答:

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


实现:

接口、动态库同原解 [url]http://cloverprince.iteye.com/blog/481309[/url] ,新的主程序如下:
#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,0,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 0;
}



编译:
GLib程序的编译可以利用pkg-config辅助设置编译参数
[quote]gcc $(pkg-config --cflags --libs glib-2.0 gmodule-2.0) -o main main.c[/quote]


执行结果略。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值