Last active
June 2, 2016 14:45
-
-
Save lniwn/0e4afa1b1f52585088f44ce1679313a2 to your computer and use it in GitHub Desktop.
使用c++11的function包装dll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <string> | |
#include <map> | |
#include <functional> | |
#ifndef WIN32_LEAN_AND_MEAN | |
#define WIN32_LEAN_AND_MEAN | |
#endif | |
#include <windows.h> | |
namespace C0xHelper | |
{ | |
class DllHelper | |
{ | |
public: | |
DllHelper() :dllModule_(nullptr) | |
{} | |
~DllHelper() | |
{ | |
Unload(); | |
} | |
bool Load(const std::wstring& dllPath) | |
{ | |
dllModule_ = ::LoadLibraryW(dllPath.c_str()); | |
return dllModule_ != nullptr; | |
} | |
bool Unload() | |
{ | |
if (!dllModule_) | |
{ | |
return true; | |
} | |
if (!::FreeLibrary(dllModule_)) | |
{ | |
return false; | |
} | |
dllModule_ = nullptr; | |
return true; | |
} | |
template<typename T> | |
std::function<T> GetFunction(const std::string& funcName) | |
{ | |
auto itFunc = funcMap_.find(funcName); | |
if (itFunc != funcMap_.end()) | |
{ | |
return std::function<T>(reinterpret_cast<T*>(itFunc->second)); | |
} | |
auto funcAddr = ::GetProcAddress(dllModule_, funcName.c_str()); | |
if (!funcAddr) | |
{ | |
return nullptr; | |
} | |
funcMap_.insert(std::make_pair(funcName, funcAddr)); | |
return std::function<T>(reinterpret_cast<T*>(funcAddr)); | |
} | |
template<typename T, typename... Args> | |
typename std::result_of<std::function<T>(Args...)>::type | |
CallFunction(const std::string& funcName, Args&&... args) | |
{ | |
auto func = GetFunction<T>(funcName); | |
if (!func) | |
{ | |
throw std::logic_error(funcName.c_str()); | |
} | |
return func(std::forward<Args>(args)...); | |
} | |
private: | |
HMODULE dllModule_; | |
std::map<std::string, FARPROC> funcMap_; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment