Windows下动态加载dll库

库代码、

声明

class handle //接口类
{

public:
	virtual void run() = 0;
	virtual void stop() = 0;
	virtual void pause() = 0;
};

#pragma once
#ifdef LIBDLL
#define LIBDLL _declspec(dllexport)
#else
#define LIBDLL _declspec(dllexport)
#endif
#include "handle.h"
class LIBDLL exporeDll:public handle
{
public:
	virtual void run();
	virtual void stop();
	virtual void pause();
};

实现

#include "pch.h"
#include "exporeDll.h"
#include <iostream>
void exporeDll::run()
{
	std::cout << "跑" << std::endl;
}
void exporeDll::stop()
{
	std::cout << "停止" << std::endl;
}
void exporeDll::pause()
{
	std::cout << "暂停" << std::endl;
}

extern "C" LIBDLL handle*getInstance()
{
	return new exporeDll();
}


动态加载库文件

#include "../生成动态库/handle.h"
#include <Windows.h>
#include <QDebug>
#include <QString>
#include <QList>
#include <QDir>
#include <QFileInfo>
class dllClass
{
public:
	dllClass();
	~dllClass();
	bool loadModel(QString fliePath = nullptr);
	void start();
private:
	QList<HINSTANCE>m_hDll;
	QList<handle*>m_handle;
};
using _hand = handle * (*)();
bool dllClass::loadModel(QString fliePath)
{
	QDir dir;
	QStringList filter{ "*.dll" };

	if (fliePath == nullptr)
	{
		//QDir dir(QDir::currentPath());
		dir.setPath(QDir::currentPath());
	}
	else
	{
		dir.setPath(fliePath);
	}// end of if

	dir.setNameFilters(filter);
	auto fileInfo = dir.entryInfoList(filter); //过滤dll文件

	for (auto &name : fileInfo)
	{
		auto hDll = LoadLibraryA(((name.fileName().toStdString().c_str())));
		if (NULL == hDll)
		{
			continue;
		}//end of if

		m_hDll.push_back(hDll);

		auto hand_ = (_hand)GetProcAddress(hDll, "getInstance");
		if (NULL == hand_)
		{
			continue;
		}//end of if

		auto hadle__ = hand_(); //这里取出来的是一个对象
		m_handle.push_back(hadle__); //遍历的类放入有List容器中

	}//end of for

	return true;
}
上一篇:ROS2学习之旅(21)——创建一个动作服务和客户节点(C++)


下一篇:在Mac OS X上无法使用C + libusb声明USB接口