CTK-安装插件的方式

方式1:使用ctk框架工厂,适用于调用普通的插件

ctkPluginFrameworkFactory frameworkFactory;
QSharedPointer<ctkPluginFramework> framework = frameworkFactory.getFramework();
// 初始化并启动插件框架
try {
    framework->init();
    framework->start();
    qDebug() << "CTK plugin framework start...";
} catch (const ctkPluginException &e) {
    qDebug() << "CTK plugin framework init err: " << e.what();
    return -1;
}

// 获取插件服务的contex
ctkPluginContext* pluginContext = framework->getPluginContext();
try {
    // 安装插件
    QSharedPointer<ctkPlugin> plugin = pluginContext->installPlugin(QUrl::fromLocalFile(pluginPath));
    qDebug() << QString("Plugin[%1_%2] installed...").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());
    // 启动插件
    plugin->start(ctkPlugin::START_TRANSIENT);
    qDebug() << "Plugin start...";
} catch (const ctkPluginException &e) {
    qDebug() << QString("Failed install or run plugin: ") << e.what() << e.getType();
    return -2;
}

// 获取服务引用

ctkServiceReference reference = pluginContext->getServiceReference<AbsLogService>();
if (reference) {
    // 获取指定 ctkServiceReference 引用的服务对象
    AbsLogService* service = qobject_cast<AbsLogService*>(pluginContext->getService(reference));
    if (service != Q_NULLPTR) {
        // 调用服务
        service->log("123");
    }
}
else {
    qDebug()<<"reference is null";
}

方式2:使用ctk框架启动器,适用于需要eventadmin时

QString path = QDir::currentPath() + "/third_libs/ctk/libs";
// 在插件的搜索路径列表中添加一条路径
ctkPluginFrameworkLauncher::addSearchPath(path);
ctkPluginFrameworkLauncher::start("org.commontk.eventadmin");
// 获取插件上下文
ctkPluginContext* context = ctkPluginFrameworkLauncher::getPluginContext();
// 启动插件 BlogEventHandler
try {
    QSharedPointer<ctkPlugin> plugin = context->installPlugin(QUrl::fromLocalFile(pluginPath1));
    plugin->start(ctkPlugin::START_TRANSIENT);
    qDebug() << "BlogEventHandler start ...";
} catch (const ctkPluginException &e) {
    qDebug() << "Failed to start BlogEventHandler" << e.what();
}
// 启动插件 BlogManager
try {
    QSharedPointer<ctkPlugin> plugin = context->installPlugin(QUrl::fromLocalFile(pluginPath2));
    plugin->start(ctkPlugin::START_TRANSIENT);
    qDebug() << "BlogManager start ...";
} catch (const ctkPluginException &e) {
    qDebug() << "Failed to start BlogManager" << e.what();
}
// 停止插件
ctkPluginFrameworkLauncher::stop();

 

posted @ 2020-07-03 09:41  朱小勇  阅读(1809)  评论(0编辑  收藏  举报