PDA

View Full Version : Multiple instance of Plugin object



mcosta
15th June 2011, 11:58
Hi,

can I instantiate multiple object of a plugin class?
I show you a prototype of code I'd like to use



QPluginLoader loader (pluginDir.absoluteFilePath (fileName));

QObject *instance = loader.instance ();
QObject *newObj = 0;
QMetaObject *mo = 0;
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



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



class HelloWorldPlugin: public QObject, IExample
{
Q_OBJECT
Q_INTERFACES (IExample)

public:
HelloWorldPlugin(QObject *parent = 0);

QString messageString () const;
};




HelloWorldPlugin::HelloWorldPlugin(QObject *parent)
: QObject (parent)
{
}

QString HelloWorldPlugin::messageString() const
{
return QString("Hello World");
}

Q_EXPORT_PLUGIN2 (HelloWorldPlugin, HelloWorldPlugin)


the output is



HelloWorldPlugin plugin says: "Hello World"
Create New Instance Failed
Found 1 entries

joyer83
15th June 2011, 13:41
It says in Qt's documentation at QMetaObject::newInstance() this:

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.

wysota
15th June 2011, 15:42
Usually you make the plugin a factory that can return instances of interfaces you need:


class MyPluginIface : ... {
// ...
public:
virtual MyRealIface * create() = 0;
}

Then you can create as many instances of MyRealIface as you want.

mcosta
15th June 2011, 17:11
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.