Qt的
插件使用起来非常简单,但是如果在某些平台上,并不想用Qt库,则需要自己实现类似的功能
以下是一个简单的实现:3个宏
1、实现插件:
定义插件类的
头文件:
class IPlugin{...}
实现:class IPluginImpl : public IPlugin{...}
在头文件里声明:
Pan_Declare_Plugin(IPlugin) 在实现文件里:
Pan_Export_Plugin(IPlugin, IPluginImpl )
2、load插件:
在需要load的地方,PanLoadPlugin(IPlugin),声明一个loadIPlugin函数
IPlugin*ipulin = loadIPlugin(filename);
3、代码:
宏定义
- #define Pan_Declare_Plugin(baseclass) extern "C"{\
- PAN_EXPORTS baseclass *create_##baseclass();};
- #define Pan_Export_Plugin(baseclass, implclass) extern "C"{\
- baseclass *create_##baseclass(){return new implclass;}};
panlibrary.h
- #pragma once
- #ifdef _WIN32
- #include <Windows.h>
- #include <iostream>
- #endif
- class PanLibrary
- {
- public:
- PanLibrary();
- ~PanLibrary();
- #ifdef _WIN32
- typedef FARPROC symbol_type;
- #else
- typedef void* symbol_type;
- #endif
- symbol_type loadEntryPoint(const std::string&);
- bool load(const std::string&);
- symbol_type getSymbol(const std::string&);
- const std::string& getErrorMessage() const;
- private:
- #ifdef _WIN32
- HINSTANCE _hnd;
- #else
- void* _hnd;
- #endif
- std::string _err;
- };
- #define PanLoadPlugin(baseclass)\
- baseclass *load##baseclass(std::string fn)\
- {\
- typedef baseclass *(*FUN)(); \
- PanLibrary lib;\
- PanLibrary::symbol_type ret = lib.loadEntryPoint(fn + ":create_" + #baseclass);\
- if(ret)\
- {\
- FUN f = FUN(ret);\
- return f();\
- }\
- return NULL;\
- }
panlibrary.cpp