C-language dynamic Call Library

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.