Java教程

Windows下动态加载dll库

本文主要是介绍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;
}
这篇关于Windows下动态加载dll库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!