首页 > 代码库 > AutoSharedLibrary -- 基于模板元编程技术的跨平台C++动态链接加载库

AutoSharedLibrary -- 基于模板元编程技术的跨平台C++动态链接加载库

 基于模板元编程技术的跨平台C++动态链接加载库。通过模板技术,使用者仅需通过简单的宏,即可使编译器在编译期自动生成加载动态链接库导出符号的代码,无任何额外的运行时开销。


ASL_LIBRARY_BEGIN(TestLib) 
    ASL_SYMBOL(Proc_test1, test1, false) 
    ASL_SYMBOL(Proc_test2, test2, true)
ASL_LIBRARY_END() 

TestLib theLib;
try { theLib.Load("./1.so"); }
catch (ASL::LibraryNotFoundException& e)
{
    cout << e.what() << endl; // 输出./1.so 
} 
catch (ASL::SymbolNotFoundException& e) 
{
    cout << e.what() << endl; // 输出 加载失败的符号名称 
 }

theLib.test1(1); // assert(theLib.test1 != NULL) 
theLib.test2("aa"); 
theLib.Unload();


假定有个一个名为1.so的动态链接库,并且该模块导出test1和test2两个接口。test1的接口类型为Proc_test1, test2的接口类型为Proc_test2。

ASL_SYMBOL宏的第三个参数表示,如果该符号加载失败(模块并没有导出该接口),是否抛出SymbolNotFoundException。 为false时,抛出异常,终止链接库加载流程,并且e.what()为加载失败的符号名称。为true时,忽略错误,仍然继续加载其他符号,客户端可以根据对应的接口是否为NULL来判断该符号是否加载成功。


/********************************************************************
	created:	2014/05/31
	file base:	AutoSharedLibrary
	file ext:	h
	author:		qiuhan (hanzz2007@hotmail.com)
	
	purpose:	Cross platform classes and macros to make  dynamic link module
                easy to use by using c++ template meta programming technic.

                No need to make any changes to existing module code.

                Support both windows(*.dll) and linux(*.so) platforms (wchar_t & char).
                
                SPECIAL THANKS TO TRL (Template Relection Library)
                
    usage:      
                Following codes are all in client side:

                ASL_LIBRARY_BEGIN(ClassName)
                    ASL_SYMBOL(Proc_func1, func1, true)
                    ASL_SYMBOL(Proc_func2, func2, false)
                ASL_LIBRARY_END()
                
                ClassName theLib;
                try {
                    theLib.Load("./1.so");
                } 
                catch (ASL::LibraryNotFoundException& e) {
                }
                catch (ASL::SymbolNotFoundException& e) {
                }
                theLib.func1(1);
                theLib.func2("aa");
                theLib.Unload();


*********************************************************************/

#ifndef ASL_INCLUDE_H
#define  ASL_INCLUDE_H

#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif

#include <cstdlib>
#include <exception>
#include <string>

namespace ASL {

    namespace Private {

        template <class Head_, class Tail_>
        struct TypeList
        {
            typedef Head_ Head;
            typedef Tail_ Tail;
        };

        class NullType {};

        template <int i_>
        struct Int2Type
        {
            enum { value = http://www.mamicode.com/i_ };>