我有一个基本上是插件管理器的应用程序。此应用程序应该能够处理具有相同接口但行为不同的任意数量的插件。
为实现这一目标,插件具有以下类层次结构:
在这个最小的例子中,每个插件只有两个方法:getName
返回硬编码字符串,geId
返回存储在文本文件中的字符串,该文件将被编译成每个插件的资源文件
事情是:每个插件返回其硬编码名称。但返回的Id是两个情况下第一个插件的ID(请参阅输出)。
为什么?这是代码和应用程序输出:
应用输出
############# Plugin load ok #############
"Plugin01"
"p01"
############# Plugin load ok #############
"Plugin02"
"p01"
############# ready #############
的main.cpp
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDir dir(QCoreApplication::applicationDirPath());
foreach(QString fileName, dir.entryList(QDir::Files))
{
QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader.instance();
if(plugin)
{
qDebug() << endl << "############# Plugin load ok #############";
if(dynamic_cast<IPlugin* >(plugin))
{
qDebug() << dynamic_cast<IPlugin* >(plugin)->getName();
qDebug() << dynamic_cast<IPlugin* >(plugin)->getId();
}
}
}
qDebug() << "############# ready #############";
return a.exec();
}
IPlugin.h
class IPlugin : public QObject
{
Q_OBJECT
public:
IPlugin(QObject *parent = 0) : QObject(parent) {}
virtual ~IPlugin() {}
virtual QString getId() = 0;
virtual QString getName() = 0;
};
IPlugin01.h
class IPlugin01 : public IPlugin
{
public:
IPlugin01(QObject *parent) : IPlugin(parent) {}
virtual ~IPlugin01() {}
};
QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(IPlugin01,
"Plugin01/0.1");
QT_END_NAMESPACE
Plugin01.h
class Plugin01 : public IPlugin01
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "Plugin01/0.1")
Q_INTERFACES(IPlugin01)
public:
Plugin01(QObject *parent = 0);
virtual QString getId();
virtual QString getName();
};
Plugin01.cpp
Plugin01::Plugin01(QObject *parent) :
IPlugin01(parent)
{
}
QString Plugin01::getId()
{
QFile file(":/id.txt");
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return file.readAll();
}
return "";
}
QString Plugin01::getName()
{
return "Plugin01";
}
插件01资源文件的id.txt
p01
IPlugin02.h
class IPlugin02 : public IPlugin
{
public:
IPlugin02(QObject *parent) : IPlugin(parent) {}
virtual ~IPlugin02() {}
};
QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(IPlugin02,
"Plugin02/0.1");
QT_END_NAMESPACE
Plugin02.h
class Plugin02 : public IPlugin02
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "Plugin02/0.1")
Q_INTERFACES(IPlugin02)
public:
Plugin02(QObject *parent = 0);
virtual QString getId();
virtual QString getName();
};
Plugin02.cpp
Plugin02::Plugin02(QObject *parent) :
IPlugin02(parent)
{
}
QString Plugin02::getId()
{
QFile file(":/id.txt");
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return file.readAll();
}
return "";
}
QString Plugin02::getName()
{
return "Plugin02";
}
来自Plugin02资源文件的id.txt
p02
答案 0 :(得分:2)
资源路径是&#34;全局&#34;,因此,:/id.txt
不正确。您应该以其他方式设计资源结构。或者您应该手动加载资源。