如何使用QPluginLoader从QByteArray加载插件

How to load a plugin with QPluginLoader from a QByteArray

本文关键字:加载 插件 QByteArray 何使用 QPluginLoader      更新时间:2023-10-16

QPluginLoader类不提供从QByteArray加载Qt插件的方法。如何从QByteArray加载插件?

在我的例子中,插件是通过stdin发送到程序的。这就是为什么它们不能作为文件使用。

您可以先将QByteArray保存到QTemporaryFile,然后用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());
  }
}

不幸的是,如果您有多个插件,并且需要多次运行我们的函数load_plugin_from_bytearray,这可能不起作用,因为QTemporaryFile可能会为临时文件重用相同的文件路径,而QPluginLoader正在缓存其加载的插件。我需要对此进行更多的调查。无论如何,您可以通过为每个QTemporaryFile 提供不同的templateName来使临时文件路径唯一,从而避免这个问题

QTemporaryFile::QTemporaryFile(const QString & templateName)