Exetools  

Go Back   Exetools > General > Source Code

Notices

Reply
 
Thread Tools Display Modes
  #1  
Old 04-14-2018, 08:39
bugficks bugficks is offline
Friend
 
Join Date: Apr 2018
Posts: 8
Rept. Given: 0
Rept. Rcvd 0 Times in 0 Posts
Thanks Given: 3
Thanks Rcvd at 14 Times in 8 Posts
bugficks Reputation: 0
just for the fun of it, a c++14 version

PHP Code:
#include <string>
#include <memory>
#include <map>
#include <system_error>

template <typename Ftypename... ArgTypes>
auto DynCallT(LPCTSTR libNameLPCSTR funcNameArgTypes... args)
{
    
using tstring std::basic_string<TCHARstd::char_traits<TCHAR>, std::allocator<TCHAR>>;
    
using lib_ptr std::shared_ptr<std::remove_pointer_t<const HMODULE>>;
    
using lib_map std::map<const tstringlib_ptr>;

    static 
lib_map libMap;

    
HMODULE h nullptr;
    const 
auto &libMap.find(libName);
    if(
!= libMap.end())
        
l->second.get();
    else if((
= ::LoadLibrary(libName)) != nullptr)
        
libMap[libName] = lib_ptr(h, ::FreeLibrary);
    else
        throw 
std::system_error(std::make_error_code(std::errc::invalid_argument));

    
F f reinterpret_cast<F>(::GetProcAddress(hfuncName));
    if(!
f)
        throw 
std::system_error(std::make_error_code(std::errc::function_not_supported));

    return 
f(args...);

usage:
PHP Code:
    // using 'decltype' when you have a prototype 
    
auto r DynCallT<decltype(&MessageBoxA)>(_T("user32"), "MessageBoxA"nullptr"123""321"0);

    
// or using func decl as template arg
    
auto tc1 DynCallT<DWORD(WINAPI*)()>(_T("kernel32"), "GetTickCount");

    
// using "i dont give a shit" decl :)
    
auto tc2 DynCallT<void*(WINAPI*)(...)>(_T("kernel32"), "GetTickCount"1"asd");

    
void WINAPI blub(DWORD);
    
DynCallT<decltype(&blub)>(_T("kernel32"), "Sleep"0); 
Reply With Quote
The Following 3 Users Say Thank You to bugficks For This Useful Post:
Indigo (07-19-2019), niculaita (04-14-2018), tonyweb (05-09-2018)
  #2  
Old 04-14-2018, 18:04
mcp mcp is offline
Friend
 
Join Date: Dec 2011
Posts: 73
Rept. Given: 4
Rept. Rcvd 12 Times in 11 Posts
Thanks Given: 7
Thanks Rcvd at 47 Times in 35 Posts
mcp Reputation: 12
What is C++14 specific about this code?
One drawback is that it's not thread safe.
Reply With Quote
The Following User Says Thank You to mcp For This Useful Post:
Indigo (07-19-2019)
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On


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


All times are GMT +8. The time now is 01:58.


Always Your Best Friend: Aaron, JMI, ahmadmansoor, ZeNiX, chessgod101
( Since 1998 )