Multiple instance of Plugin object
Hi,
can I instantiate multiple object of a plugin class?
I show you a prototype of code I'd like to use
Code:
QObject *instance
= loader.
instance ();
if (instance) {
IExample *plugin = qobject_cast<IExample*>(instance);
if (plugin) {
qDebug() << instance->metaObject ()->className () << "plugin says:"
<< plugin->messageString ();
newObj = instance->metaObject ()->newInstance (0);
if (0 != newObj)
qDebug () << "Create New Instance OK";
else
qDebug () << "Create New Instance Failed";
}
}
where IExample is defined
Code:
class IExample
{
public:
virtual ~IExample () {}
virtual QString messageString
() const = 0;
};
Q_DECLARE_INTERFACE (IExample, "local.costa.IExample/1.0")
and this is the loaded plugin
Code:
class HelloWorldPlugin
: public QObject, IExample
{
Q_OBJECT
Q_INTERFACES (IExample)
public:
HelloWorldPlugin
(QObject *parent
= 0);
};
Code:
HelloWorldPlugin
::HelloWorldPlugin(QObject *parent
){
}
QString HelloWorldPlugin
::messageString() const {
}
Q_EXPORT_PLUGIN2 (HelloWorldPlugin, HelloWorldPlugin)
the output is
Code:
HelloWorldPlugin plugin says: "Hello World"
Create New Instance Failed
Found 1 entries
Re: Multiple instance of Plugin object
It says in Qt's documentation at QMetaObject::newInstance() this:
Quote:
Note that only constructors that are declared with the Q_INVOKABLE modifier are made available through the meta-object system.
I don't see this Q_INVOKABLE macro used in your source code. Try adding it and see what happens.
Re: Multiple instance of Plugin object
Usually you make the plugin a factory that can return instances of interfaces you need:
Code:
class MyPluginIface : ... {
// ...
public:
virtual MyRealIface * create() = 0;
}
Then you can create as many instances of MyRealIface as you want.
Re: Multiple instance of Plugin object
Thank you for the answer.
Your solution is more elegant than than mine.
I was courious about QMetaObject::newInstance().
I solved using joyer83 tips but for a real solution I'll use the factory.