LibraryLoader.h 1.9 KB

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