![]() |
|
|
|
#1
|
|||
|
|||
|
Taking what I said previously into account, a much safer variant could look like this:
Code:
template < typename RetType, typename... ArgTypes >
RetType DynCall(const char* dll_name, const char* api_name, ArgTypes...args) {
typedef RetType(__stdcall* F)(ArgTypes...);
HMODULE module = LoadLibrary(dll_name);
assert(module != INVALID_MODULE_HANDLE && "Failed to load library");
F fptr = (F)GetProcAddress(module, api_name);
assert(fptr && "Unable to resolve API");
return fptr(args...);
}
Code:
int main() {
std::cout << "GetTickCount1: "
<< DynCal< DWORD >("kernel32.dll", "GetTickCount") << "\n";
DynCall< VOID, DWORD >("kernel32.dll", "Sleep", 1000);
std::cout << "GetTickCount2: "
<< DynCall< DWORD >("kernel32.dll", "GetTickCount") << "\n"
}
produces this output: Code:
GetTickCount1: 16462234 GetTickCount2: 16463250 Press any key to continue . . . The advantage here is that the compiler does all the type checking for you, so this cannot fail unless you mess up the function prototype itself - but that problem cannot be fixed anyhow unless we're using a correct import library which would defeat the whole purpose of this exercise. Things to improve:
Edit: the template argument do not display correctly due to forum system :/ I fixed it by adding a blank to the template arguments, now it displays correctly. Last edited by mcp; 04-06-2018 at 18:37. |
![]() |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Calling any function dynamically without typedef | Succubus | Source Code | 0 | 10-21-2021 16:34 |
| WinAPI: No WM_COMMAND Message? | aldente | General Discussion | 2 | 07-05-2006 07:17 |