Guitar
LoadPlugin.h
Go to the documentation of this file.
1 #ifndef LOADPLUGIN_H
2 #define LOADPLUGIN_H
3 
4 #include <Logger.h>
5 #include <QCoreApplication>
6 #include <QPluginLoader>
7 #include <QString>
8 #include <joinpath.h>
9 #include <memory>
10 
11 template <typename ImplType, typename Interface> std::shared_ptr<ImplType> loadPlugin(std::string name)
12 {
13  std::shared_ptr<ImplType> ret;
14 
15 #ifdef QT_DEBUG
16  name.push_back('d');
17 #endif
18 
19 #ifdef Q_OS_WIN
20  QString path = QString::fromStdString(name);
21 #else
22  QString path = QCoreApplication::applicationDirPath() / QString::fromStdString("../lib/lib" + name + ".so");
23 #endif
24 
25  char const *const c_name = name.c_str();
26 
27  logprintf(LOG_DEFAULT, "loading the plugin %s", path.toStdString().c_str());
28  QPluginLoader loader(path);
29  Interface *plugin = dynamic_cast<Interface *>(loader.instance());
30  if (plugin) {
31  ret = std::shared_ptr<ImplType>(plugin->create());
32  if (ret->open()) {
33  qDebug() << QString::asprintf("%s is loaded successfully.", c_name);
34  } else {
35  qDebug() << QString::asprintf("Failed to load the plugin %s", c_name);
36  return {};
37  }
38  } else {
39  qDebug() << loader.errorString();
40  return {};
41  }
42 
43  return ret;
44 }
45 
46 
47 #endif // LOADPLUGIN_H
std::shared_ptr< ImplType > loadPlugin(std::string name)
Definition: LoadPlugin.h:11
#define logprintf(LEVEL, FMT,...)
Definition: Logger.h:61
#define LOG_DEFAULT
Definition: Logger.h:5