C ++ template package Win32 API Dynamic Invocation

Due

Spent two weeks read through "C ++ Primer", the accumulation of doubts swept away.

Antecedents

The use of C ++ 11 variable template package call dll exported functions
thought has been well spent, time to consolidate at recent knowledge, found himself Daoxing enough!

new plan

Full use of the function template argument inference, made "similar dynamic language" experience.

#include <windows.h>

class WinDll
{
public:
    WinDll(const char* dll) : mLib(::LoadLibraryA(dll)) {}
    WinDll(const wchar_t* dll) : mLib(::LoadLibrary(dll)) {}
    ~WinDll() { FreeLibrary(mLib); }

    WinDll(const WinDll&) = delete;
    WinDll& operator=(const WinDll&) = delete;

    operator bool() { return !!mLib; }

    template <typename Ret, typename... Args>
    Ret Invoke(const char* name, const Args& ...args)
    {
        auto proc = GetProcAddress(mLib, name);
        typedef Ret(__stdcall* Func)(Args...);
        return (proc) ?  reinterpret_cast<Func>(proc)(args...) : (Ret());
    }

private:
    HMODULE mLib;
};

int main()
{
    WinDll user32("user32");
    if (user32) {
        user32.Invoke<int>("MessageBoxA", 0, 0, 0, 0);
        user32.Invoke<int, HWND, LPCWCHAR, LPCWCHAR>("MessageBoxW", NULL, L"Hello World!", L"Demo", MB_ICONINFORMATION | MB_OK);
    }
}

Impressions

After fine chemicals semantics in C ++, so simple!
Over the years simply blame their own projects to solve the problem, ignoring the most basic semantic connotation!

Guess you like

Origin www.cnblogs.com/wuyaSama/p/12452688.html