Transferred from: http://cloverprince.iteye.com/blog/481309
An existing main program is written in C language. Now to allow third-party developers to write extended modules, a third-party-developed module must provide a list of known-named functions (such as foo (), bar (), Baz ()). If a third-party module must be published separately from the main program's binary code, the DLL or so can be dynamically loaded and used in a folder, how should it be implemented?
In addition to the interface provided by the operating system, the glib can also be used in a simple package. GLib simply encapsulates the operating system-related dynamic library load function, which is located in Gmodule. Gmodule equivalent to the library
Handle, while G_module_open, G_module_symbol, and g_module_close respectively correspond to Dlopen, Dlsym, and Dlclose functions.
interface, dynamic library and the original solution http://cloverprince.iteye.com/blog/481309, the new main program is as follows:
#include <stdio.h>#include<stdlib.h>#include<glib.h>#include<glib/gstdio.h>#include<gmodule.h>#include"plugin-interface.h"Const Char*ConstPlugins_path ="Plugins";intMainintargcChar**argv) {Gdir*dir; ConstGchar *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;}
Compile:
Compilation of the glib program can be compiled with Pkg-config auxiliary settings
Reference
GCC $ (pkg-config--cflags--libs glib-2.0 gmodule-2.0)-O main main.c
C-Language dynamic Call library (GO)