【C++】动态导入Windows系统API的简单方法
源码
从chromium源码学习到的非常方便动态导入Windows系统API的方法,摘录在这里,方便查找。
FARPROC GetFunctionInternal(const wchar_t* library, const char* function)
{HMODULE module = LoadLibrary(library);if (!module) {return nullptr;}// Strip off any leading :: that may have come from stringifying the// function’s name.if (function[0] == ':' && function[1] == ':' && function[2] && function[2] != ':') {function += 2;}FARPROC proc = GetProcAddress(module, function);return proc;
}template <typename FunctionType>
FunctionType* GetFunction(const wchar_t* library, const char* function)
{return reinterpret_cast<FunctionType*>(GetFunctionInternal(library, function));
}#define GET_FUNCTION(library, function) \GetFunction<decltype(function)>( \library, #function)
使用
巧妙之处在于用模板屏蔽了系统API的函数定义,直接通过模板提取
GET_FUNCTION(L"kernel32.dll", ::SetThreadDescription)