【问题标题】:How to load a plugin with QPluginLoader from a QByteArray如何使用 QPluginLoader 从 QByteArray 加载插件
【发布时间】:2013-02-12 10:43:32
【问题描述】:

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

在我的情况下,插件通过标准输入发送到程序。这就是为什么它们不能作为文件使用的原因。

【问题讨论】:

    标签: c++ qt plugins


    【解决方案1】:

    您可以先将 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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-13
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多