windows动态加载dll库

loadLib.h

#include<map>
#include<Windows.h>
#include<functional>
#include<memory>
#include<iostream>
namespace kaa {
    
    

class LibWrap {
    
    
public:
	LibWrap ();
	~LibWrap ();
	unsigned long load(std::string file);
	template<typename T>
	std::function<T> loadsym(std::string func);
private:
	HMODULE _hdll;
	std::map<std::string, void*> _funcmap;

};
template<typename T>
inline std::function<T> LibWrap::loadsym(std::string func)
{
    
    
	std::function<T> ret;
	auto it = _funcmap.find(func.c_str());
	if (it == _funcmap.end()) {
    
    
		void* voidp = GetProcAddress(this->_hdll, func.c_str());
		ret = (T*)voidp;
		if (ret) {
    
    
			_funcmap.insert(std::make_pair(func, voidp));
		}
	}
	else {
    
    
		ret = (T*)it->second;
	}
	
	return ret;
}
}

loadLib.cpp

#pragma once
#include"LoadLibrary_Wrap.h"

kaa::LibWrap::LibWrap():_hdll(NULL)
{
    
    
}

kaa::LibWrap::~LibWrap()
{
    
    
	if (_hdll) {
    
    
		FreeLibrary(_hdll);
	}
}

unsigned long kaa::LibWrap::load(std::string file)
{
    
    
	DWORD r=0;
	if (this->_hdll) {
    
    
		FreeLibrary(this->_hdll);
		r = GetLastError();
		if (r) {
    
    
			return r;
		}
	}
	auto hdll = LoadLibraryA(file.c_str());
	this->_hdll = hdll;
	r = GetLastError();
	return r;
}

使用

 kaa::LibWrap libwrap;
 libwrap.load("your.dll");
 auto verfunc = libwrap.loadsym<void (const char** result)>("Your_function");
 const char* ver_result=nullptr;
 verfunc(&ver_result);

猜你喜欢

转载自blog.csdn.net/idream68/article/details/118800544