开发中经常需要动态调用一些导出函数,总想封装后使用
常规使用
typedef int WINAPI (*TMessageBoxA)(HWND hWnd,LPCSTR lpText,LPCSTR lpCaption,UINT uType);
HMODULE m = LoadLibraryA("user32");
FARPROC fn = GetProcAddress(m,"MessageBoxA");
TMessageBoxA msgBox = reinterpret_cast<TMessageBoxA>(fn);
msgBox(0,0,0,0);
FreeLibrary(m);
流程很清晰,只是写多了看着不爽 ;-)
之前利用 decltype function bind 也实现过一个版本,
但用起来总觉得太重,雾里看花,这次尝试更纯粹一些
参考std::function实现方式,仅使用"Variadic Templates"
#include <windows.h>
template<typename _T> class Api;
template<typename _Res, typename... _ArgTypes>
class Api<_Res(_ArgTypes...)> {
public:
Api(const char* dllName, const char* funcName) {
_M_module = LoadLibraryA(dllName);
_M_func = reinterpret_cast<_Func>(GetProcAddress(_M_module, funcName));
}
~Api() {
if (_M_module) FreeLibrary(_M_module);
}
_Res operator()(_ArgTypes... __args) const {
return _M_func(__args...);
}
private:
typedef _Res (*_Func)(_ArgTypes...);
_Func _M_func;
HMODULE _M_module;
};
int main()
{
Api<int(HWND,LPCTSTR,LPCTSTR,UINT)> msgbox("user32", "MessageBoxA");
msgbox(0,0,0,0);
}
注意,为了最小利用特性,这里没有利用final、delete进行使用限制,也没有对HMODULE进行缓存管理,生产环境请自行抉择。
有更好的方式,请留言交流;-)
原文:https://www.cnblogs.com/wuyaSama/p/11510889.html