Erik Sjölund
Erik Sjölund

Reputation: 11408

How to load a plugin with QPluginLoader from a QByteArray

The QPluginLoader class does not provide a method for loading the Qt plugin from a QByteArray. How can I load the plugin from a QByteArray?

The plugins are in my case sent over stdin to the program. That is why they are not available as files.

Upvotes: 1

Views: 352

Answers (1)

Erik Sjölund
Erik Sjölund

Reputation: 11408

You could first save the QByteArray to a QTemporaryFile and then load it with QPluginLoader

void load_plugin_from_bytearray(const QByteArray &array) {
  QTemporaryFile file;
  file.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
  if (file.open()) {
    qint64 bytes_written = file.write(array);
    if (bytes_written != array.size()) {
      throw std::runtime_error("Writing to temporary file failed");
    }
  } else {
    throw std::runtime_error("Could not open temporary file");
  }
  QPluginLoader loader(file.fileName());
  QObject *plugin = loader.instance();
  if (plugin) {
    do_something_with_plugin(plugin);
  } else {
    throw std::runtime_error(loader.errorString().toStdString());
  }
}

Unfortunately this might not work if you have more than one plugin and need to run our function load_plugin_from_bytearray multiple times, as QTemporaryFile might by chance be reusing the same file path for the temporary files and QPluginLoader is caching its loaded plugins. I need to investigate this more. Anyway, you could circumvent that problem by making the temporary file paths unique by providing a different templateName for each QTemporaryFile

QTemporaryFile::QTemporaryFile(const QString & templateName)

Upvotes: 2

Related Questions