zoukankan      html  css  js  c++  java
  • C语言动态调用库(转)

    转自: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,0,NULL);
    
        while(filename=g_dir_read_name(dir)) {
            GModule *module;
            char *path;
    
            InitModuleFunc init_func;
            PluginInterface iface;
    
            printf("Openning %s ...
    ",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辅助设置编译参数

    引用

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

  • 相关阅读:
    修复文件系统
    遗忘root密码,对密码进行重置
    grub引导程序破坏修复下
    模拟Grub引导故障上(配置文件损坏)
    模拟MBR故障修复
    RAID5 制作 (一个硬盘制作)
    RAID10 (硬盘制作)
    du,df区别
    07_软件的安装
    06_find-查找文件
  • 原文地址:https://www.cnblogs.com/dragonsuc/p/4270072.html
Copyright © 2011-2022 走看看