Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/***********************************************************
*
* Example based on an idea from the article "Rule of Zero"
* URL: https://blog.rmf.io/cxx11/rule-of-zero
*
* Must be compiled as C++11
************************************************************/
#define _SCL_SECURE_NO_WARNINGS
#define UNICODE
#include <iostream>
#include <memory>
#include <type_traits>
#include <Windows.h>
using namespace std;
// declare a function pointer to MessageBox API from User32.dll
using FunctionPtr = std::add_pointer<int __stdcall (HWND, LPCWSTR, LPCWSTR, UINT)>::type;
// alternative declaration
// using FunctionPtr = int (__stdcall *)(HWND, LPCWSTR, LPCWSTR, UINT);
// this class loads/unloads a DLL automatically
// no need for explicit constructors, destructor etc.
class module{
public:
explicit module(wstring const& name)
: handle { ::LoadLibraryW(name.c_str()), &FreeLibraryInternal } {}
// define a wrapper for Windows' FreeLibrary
static bool FreeLibraryInternal(void* dll) {
return (true == ::FreeLibrary(static_cast<HMODULE>(dll)));
}
private:
// declare a module_handle as unique_ptr to void + custom deleter function FreeLibraryInternal
using module_handle = unique_ptr<void, decltype(&module::FreeLibraryInternal)>;
module_handle handle;
public:
bool isValid() {
return handle != nullptr;
}
HMODULE const getHandle() {
return static_cast<HMODULE>(this->handle.get());
}
};
// function that calls the MessageBoxW API
void showMsgBox(wstring const message, module& const mod) {
if (mod.isValid()) {
FunctionPtr ptr = reinterpret_cast<FunctionPtr>(::GetProcAddress(mod.getHandle(), "MessageBoxW"));
ptr(nullptr, message.c_str(), L"Message", MB_OK);
}
}
int main(int argc, char **argv) {
// load DLL
module mod{ L"User32.dll" };
showMsgBox(L"hello", mod);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment