工程结构:
工程源码:
-------------PluginAnimal.pro------------
TEMPLATE = subdirs
SUBDIRS += \
dog \
animal
#-------------------------------------------------
#
# Project created by QtCreator 2015-07-28T14:45:07
#
#-------------------------------------------------
QT += core
QT -= gui
DESTDIR = ../../PluginAnimal/exe
TARGET = animal
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
HEADERS += \
animalinterface.h
#ifndef ANIMALINTERFACE_H
#define ANIMALINTERFACE_H
#include <QString>
#include <QtPlugin>
class AnimalInterface
{
public:
virtual QString type()=0;
virtual int age()=0;
virtual void voice()=0;
};
#define AnimalInterface_iid "org.qt-proj.Qt.Animal"
Q_DECLARE_INTERFACE(AnimalInterface, AnimalInterface_iid)
#endif // ANIMALINTERFACE_H
#include <QCoreApplication>
#include "animalinterface.h"
#include <QDebug>
#include <QPluginLoader>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"animal ...";
QPluginLoader loader(QCoreApplication::applicationDirPath().append("/dog.dll"));
QObject *obj=qobject_cast<QObject *>(loader.instance());
if(obj){
qDebug()<<"load success!";
AnimalInterface *animal=qobject_cast<AnimalInterface *>(obj);
if(animal){
qDebug()<<"type:"<<animal->type()<<", age:"<<animal->age();
animal->voice();
}else{
qDebug()<<"animal error!";
}
}else{
qDebug()<<"object error!";
}
return 0;
}
------------dog.pro-----------
#-------------------------------------------------
#
# Project created by QtCreator 2015-07-28T14:47:04
#
#-------------------------------------------------
QT -= gui
TARGET = dog
TEMPLATE = lib
DESTDIR = ../../PluginAnimal/exe
SOURCES += dog.cpp
HEADERS += dog.h
unix {
target.path = /usr/lib
INSTALLS += target
}
#ifndef DOG_H
#define DOG_H
#include "../animal/animalinterface.h"
class Dog : public QObject, AnimalInterface
{
Q_OBJECT
Q_INTERFACES(AnimalInterface)
public:
QString type();
int age();
void voice();
};
#endif // DOG_H
#include "dog.h"
#include <QDebug>
QString Dog::type()
{
return "dog";
}
int Dog::age()
{
return 9;
}
void Dog::voice()
{
qDebug()<<"dog bark!";
}
Q_EXPORT_PLUGIN2(AnimalInterface_iid, Dog)
运行效果:
(-----------完----------)