Unload plugin in Qt
The problem occurs when I try to unload the loaded plugin and load a new one. This way both plugins load correctly, but when switching them (first loaded, second unloaded and vice versa) my app crashes. What is the problem?
First I try to unload the plugin stored in the QList QPluginLoader, then I check (depdend on the id (integer) passed from the special menu to load plugins) which plugin is being loaded. First load is good (first plugin loaded, nothing is unloading at this point), second load (first plugin unload, second load), on third load I get a crash
void MainWindow::loadPluginUsingId (int plugin_id) {
foreach (QPluginLoader* pluginLoader, plugins) {
pluginLoader->unload();
delete pluginLoader;
}
switch (plugin_id) {
case 0 : {
foreach (QString fileName, pluginDir.entryList(QDir::Files)) {
if (fileName == fullNameOfPlugins.value(plugin_id)) {
QPluginLoader* pluginLoader = new QPluginLoader(pluginDir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader->instance();
IndicatorInterface *indicator = qobject_cast<IndicatorInterface*>(plugin);
indicator->initIndicator();
plugins.append(pluginLoader);
}
}
}
break;
case 1 : {
foreach (QString fileName, pluginDir.entryList(QDir::Files)) {
if (fileName == fullNameOfPlugins.value(plugin_id)) {
QPluginLoader* pluginLoader = new QPluginLoader(pluginDir.absoluteFilePath(fileName));
QObject* plugin = pluginLoader->instance();
PlotterInterface *plotter = qobject_cast<PlotterInterface*>(plugin);
plotter->initPlotter();
plugins.append(pluginLoader);
}
}
}
break;
default :
break;
}
}
+3
user704010
source
to share
1 answer
foreach (QPluginLoader* pluginLoader, plugins) {
pluginLoader->unload();
delete pluginLoader; // this could be your problem
}
You need to remove the dangling pointer from your plugin list. Failure to do so will result in what you are describing.
Try the following:
while (!plugins.isEmpty()) {
QPluginLoader* pluginLoader = plugins.takeFirst();
pluginLoader->unload();
delete pluginLoader;
}
+7
source to share