您好,登录后才能下订单哦!
接口类头文件 MyPluginInterface.h
[cpp] view plain copy
#ifndef INTERFACES_H
#define INTERFACES_H
#include <QtPlugin>
#define QtPluginDemo_iid "org.qt-project.Qt.PluginDemo"
class MyPluginInterface
{
public:
virtual int add(int,int) = 0 ; // 正确写法
// virtual int add(int,int); // 不太妥的写法(虽然这也是正确的虚函数声明语句)
// 注:接口类中的虚函数都应有实体,或设置为0(推荐),这样
// C++的编译器才能为接口类生成虚函数表。否则,如果没有实现
// 接口类的虚函数也没有将其设为0,程序在在链接时可能会失败,
// 或者链接成功但最后生成的库无法加载(库中有未定义的符号)
};
Q_DECLARE_INTERFACE ( MyPluginInterface, QtPluginDemo_iid ) ;
#endif
插件头文件 MyPlugin.h
[cpp] view plain copy
#ifndef MYPLUGIN__H
#define MYPLUGIN__H
#include <QObject>
#include <QDebug>
#include "MyPluginInterface.h"
class MyPlugin : public QObject, public MyPluginInterface
{
Q_OBJECT
Q_PLUGIN_METADATA ( IID QtPluginDemo_iid FILE "MyPlugin.json")
Q_INTERFACES(MyPluginInterface)
public:
int add(int,int);
};
#endif
插件源文件 MyPlugin.cpp
[cpp] view plain copy
#include "MyPlugin.h"
int MyPlugin::add(int a , int b)
{
return a+b ;
}
#include "moc_MyPlugin.cpp"
JSON文件 MyPlugin.json,本示例中该文件是空的。
工程文件 MyPlugin.pro
[cpp] view plain copy
TEMPLATE = lib
CONFIG += plugin console
QT += core
HEADERS = MyPlugin.h MyPluginInterface.h
SOURCES = MyPlugin.cpp
OTHER_FILES = MyPlugin.json
TARGET = MyPlugin
DESTDIR = ./
INCLUDEPATH += ./
# install
target.path = ./install
INSTALLS += target
接口类头文件 MyPluginInterface.h,该文件与插件代码中的一致。
主程序文件 main.cpp
[cpp] view plain copy
#include "MyPluginInterface.h"
#include <QtPlugin>
#include <QApplication>
#include <QWidget>
#include <QPluginLoader>
#include <QString>
#include <QtDebug>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget w;
QObject* object ;
w.show();
app.addLibraryPath(QString("../MyPlugin/install")); // 添加库路径
// 加载插件,取得实例
QPluginLoader l(QString("MyPlugin")) ;
//QPluginLoader l(QString("libMyPlugin.so")) ;
if ( (object=l.instance()) != NULL )
{
qDebug("plugin loaded .");
// 使用插件
int a = 14 , b = 23 ;
MyPluginInterface* plugin = qobject_cast<MyPluginInterface*>(object) ;
if (plugin)
qDebug("%d + %d = %d",a,b,plugin->add(a,b));
}
else
{
qDebug("failed to load plugin !! ");
QString errorStr = l.errorString();
qDebug()<<errorStr;
}
return app.exec();
}
MyApp.pro
[cpp] view plain copy
######################################################################
# Automatically generated by qmake (3.0) ?? 11? 19 02:26:33 2014
######################################################################
TEMPLATE = app
QT += gui core widgets
CONFIG += console
TARGET = MyApp
INCLUDEPATH += .
# Input
HEADERS += MyPluginInterface.h
SOURCES += main.cpp
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。