PDA

View Full Version : How to instantiate a class if I dont know its name?



anoraxis
12th March 2012, 16:51
Hi:

The application I'm trying to develop must be extended using plugins. I have a XML file similar to this (I omitted some non important parts):

<program>
<component type="plugin1"/>
<component type="plugin2"/>
<component type="plugin1"/>
<component type="plugin3"/>
</program>

So, for each <component> element that I read I create a new page on a QStackedWidget containing a custom widget defined by the classes Plugin1, Plugin2 and Plugin3. Is very easy when I know the names of all the plugins because I can do something like:


class AbstractPlugin : public QObject{
//...
virtual QWidget* widget() = 0;
};

//all these classes implements "widget()"
class Plugin1 : public AbstractPlugin{/*...*/};
class Plugin2 : public AbstractPlugin{/*...*/};
class Plugin3 : public AbstractPlugin{/*...*/};

QList<AbstractPlugin* > components
QString type //this value was readed from the XML in some moment

if(type == "Plugin1")
components.append(new Plugin1());
else if(type == "Plugin2")
components.append(new Plugin2());
else if(type == "Plugin3")
components.append(new Plugin3());

foreach(AbstractPlugin* c, components){
stackedWidget->addPage(c->widget());
}

But, if I dont know the names of all the plugins because I don't write each one, how can I specify the correct constructor to call?

wysota
12th March 2012, 17:05
All you need to know is described in QPluginLoader docs and documents linked from within there. A general rule is that you know where to look for plugins and you load all the files that look like plugins and try to extract the interface you need from each loaded object.

anoraxis
12th March 2012, 17:11
Hope it works. The main advantage of my aplication depends on this.

anoraxis
20th March 2012, 15:10
Ok, I wrote some plugins that works fine but I'm facing another problem. I need to use different instances of the same plugin. It seems that each QPluginLoader that connects with the same library manages the same instance of the plugin.

I changed the way I do it. My plugin now is using the factory pattern. I have a plugin with a method that returns an instance of another class. So, the plugin project is now:

plugin.h
plugin.cpp
theClass.h
theClass.cpp
project.pro

When I build this plugin and try to load it with QPluginLoader, the plugin dosn't load. If I remove the theClass.h and cpp files from the project and build it, the plugin loads but when using I get an "unknow symbol" error.

I need some help with this. It's a problem related with the software I have to deliver to graduate from university.

amleto
20th March 2012, 20:11
you could post some code...

ChrisW67
20th March 2012, 21:42
A factory is the approach to take.

"...the plugin dosn't load.", is not a sufficient description of the problem to allow us to help. Make sure you do a clean rebuild of the plugin and, if the interfaces have changed, the application using it.