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);