dll 创建与调用
- 建立 dll 项目
①.新建项目,选择 C++ Library
②.类型选择 Shared Library
③.在头文件添加导出函数
#ifndef DLLEXAMPLE_H
#define DLLEXAMPLE_H
#include "dllExample_global.h"
class DLLEXAMPLE_EXPORT DllExample
{
public:
DllExample();
virtual ~DllExample(){};
virtual int addFunc(int a,int b);
};
//导出函数
extern "C" DLLEXAMPLE_EXPORT void helloworld();
extern "C" DLLEXAMPLE_EXPORT DllExample * getDllExample();
extern "C" DLLEXAMPLE_EXPORT void deleteDllExample(DllExample * objptr);
#endif // DLLEXAMPLE_H
④.实现导出方法
#include "dllexample.h"
#include <QDebug>
DllExample::DllExample()
{
}
int DllExample::addFunc(int a, int b)
{
return a+b;
}
DllExample *getDllExample()
{
return new DllExample();
}
void deleteDllExample(DllExample *objptr)
{
delete objptr;
objptr = nullptr;
}
void helloworld()
{
qDebug() << "helloworld";
}
⑤.构建项目,生成 dll 文件
-
动态调用 dll 导出方法
①.拷贝 dll 文件到根目录
②.方法调用
-
动态调用 dll 导出类
①.拷贝 dll 文件、接口 .h 文件到相应目录
②.方法调用
-
静态调用
①.拷贝 dll 文件、接口 .h 文件到相应目录
②.修改 pro 文件,添加路径
②.直接调用方法
plugin 创建与调用
- 创建接口头文件
①.新建项目,选择子目录项目
②.添加子项目
③.添加头文件
④.编辑头文件
#ifndef PLUGINEXAMPLEINTERFACE_H
#define PLUGINEXAMPLEINTERFACE_H
#include <QObject>
class PluginExampleInterface
{
public:
virtual ~PluginExampleInterface(){}
//接口方法
virtual QString helloworld(const QString & str) = 0;
};
//注册一个唯一标识
Q_DECLARE_INTERFACE(PluginExampleInterface,"PluginExampleInterface_1.0")
#endif // PLUGINEXAMPLEINTERFACE_H
- 创建 plugin 子项目
①.添加新的子项目
②.修改 pro 文件
③.添加接口的派生类
#ifndef PLUGINEXAMPLE_H
#define PLUGINEXAMPLE_H
#include "PluginExampleInterface.h"
class PluginExample : public QObject,PluginExampleInterface
{
Q_OBJECT
Q_INTERFACES(PluginExampleInterface)
Q_PLUGIN_METADATA(IID "PluginExampleInterface_1.0" FILE "pluginexample.json")
public:
PluginExample();
QString helloworld(const QString &str) override;
};
#endif // PLUGINEXAMPLE_H
④.实现接口方法
#include "pluginexample.h"
PluginExample::PluginExample()
{
}
QString PluginExample::helloworld(const QString &str)
{
return "hello:"+str;
}
⑤.构建子项目,生成 dll 文件
- 动态调用
①.拷贝 dll 文件到根目录
②.接口调用
#include <QCoreApplication>
#include "PluginExampleInterface.h"
#include <QDebug>
#include <QPluginLoader>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QPluginLoader pluginLoader("PluginExample.dll");
QObject *plugin = pluginLoader.instance();
if (plugin)
{
PluginExampleInterface * exp = qobject_cast<PluginExampleInterface *>(plugin);
qDebug() << exp->helloworld("123");
}
return a.exec();
}