Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
* Example based on an idea from the article "Rule of Zero"
* URL:
* Must be compiled as C++11
#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{
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)));
// 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;
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