LibraryLoader.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #pragma once
  2. //#include "FileManager.h"
  3. //#include "StringConvert.h"
  4. #include <QtCore/QLibrary>
  5. #include <QtCore/QFile>
  6. #include <QtCore/QDebug>
  7. class LibraryLoader
  8. {
  9. private:
  10. LibraryLoader()
  11. {
  12. }
  13. ~LibraryLoader()
  14. {
  15. }
  16. public:
  17. template <typename T,typename D>
  18. static D* to(T* t)
  19. {
  20. return dynamic_cast<D*>(t);
  21. }
  22. template <typename T>
  23. static T* load(std::string szPlugin)
  24. {
  25. QString szAddin = szPlugin.c_str();
  26. return load<T>(szAddin);
  27. }
  28. template <typename T>
  29. static T* load(QString szPlugin)
  30. {
  31. #ifndef _Andriod
  32. QFile file;
  33. if( file.exists(szPlugin.toStdString().c_str()) == false )
  34. //if( FileManager::ifFileExist(szPlugin.toStdString()) == false )
  35. {
  36. // qCritical() << LOG_HEADER << szPlugin << " not exist.";
  37. return NULL;
  38. }
  39. #endif
  40. T* pPlugin = NULL;
  41. QLibrary* pLoader = new QLibrary(szPlugin);
  42. if( pLoader->load() )
  43. {
  44. typedef T* (*funInterface)();
  45. funInterface fun = (funInterface)pLoader->resolve("instance");
  46. if( fun != nullptr )
  47. {
  48. pPlugin = fun();
  49. }
  50. }
  51. if( pPlugin != nullptr)
  52. {
  53. pPlugin->setLoader(pLoader);
  54. }
  55. else
  56. {
  57. QString szError = pLoader->errorString();
  58. // qCritical() << LOG_HEADER << " load " << szPlugin.toStdString().c_str() << " : " << szError.toStdString().c_str();
  59. pLoader->unload();
  60. pLoader->deleteLater();
  61. }
  62. return pPlugin;
  63. }
  64. // 释放对象
  65. // 卸载插件
  66. template <typename T>
  67. static bool unload(T* pPlugin )
  68. {
  69. if( pPlugin == nullptr )
  70. {
  71. return false;
  72. }
  73. QLibrary* pLoader = pPlugin->getLoader();
  74. if( pLoader != nullptr )
  75. {
  76. typedef void (*funDestroy)(T*);
  77. funDestroy fun = (funDestroy)pLoader->resolve("destroy");
  78. if( fun != nullptr )
  79. {
  80. fun(pPlugin);
  81. }
  82. pLoader->unload();
  83. }
  84. return true;
  85. }
  86. };