Qt插件熱加載-QPluginLoader實現

上一篇C++消息框架-基於sigslot文章中咱們講述了使用sigslot信號槽實現本身的消息框架,這是一個比較粗糙,並且小的框架。當咱們的程序逐漸變大時,咱們可能就會考慮功能插件化,或者支持某些模塊動態加載和卸載。app

功能動態加載,也就是咱們平時所說的插件化,插件支持熱插拔。框架

以前工做中,恰好接觸過這一塊的內容。下面是一個Qt加載dll的方式,當咱們把dll加載上之後,能夠嘗試轉化爲PluginInterface接口,若是能夠轉換成功,則說明咱們這個dll是咱們須要的插件,而後咱們就能夠進行插件初始化。插件

若是插件代碼須要和主程序通訊,咱們只須要在初始化插件的時候把相關參數傳遞進去便可。code

void ReadPluginsInfo( const QString & pluginsDirPath /*= ""*/ )
{
    QString pluginsPath = pluginsDirPath;
    if (pluginsDirPath.isEmpty())
    {
        pluginsPath = QApplication::applicationDirPath();
    }
    QDir pluginsDir(pluginsPath);
    pluginsDir.cd("Plugins");

    QFileInfoList pluginsFile = pluginsDir.entryInfoList(QStringList() << "*.dll", QDir::Files);
    foreach(QFileInfo fileInfo, pluginsFile)
    {
        QPluginLoader loader(fileInfo.absoluteFilePath());
        bool isLoad = loader.isLoaded();
        QString info = loader.errorString();

        if (QObject * plugin = loader.instance())
        {
            if (PluginInterface * pinterface = dynamic_cast<PluginInterface *>(plugin))
            {
                pinterface->install(PluginParam());//初始化插件
                m_lstPluginInterFace.push_back(pinterface);
            }  
        }
        else
        {
            qDebug() << loader.errorString();
        }
    }
}

上述代碼僞代碼以下:接口

void ReadPluginsInfo( const QString & pluginsDirPath /*= ""*/ )
{
    進入插件路徑
    獲取路徑下全部dll
    foreach(dll集合)
    {
        使用QPluginLoader加載動態庫文件
        if (轉化爲插件接口類)
        {
            初始化插件
        }
    }
}
相關文章
相關標籤/搜索