Simplifying Windows Registry Programming with the C++ WinReg Library

The native Windows Registry API is a C-interface API, that is low-level and kind of hard and cumbersome to use.

For example, suppose that you simply want to read a string value under a given key. You would end up writing code like this:

Sample code excerpt to read a string value from the Windows Registry using the native Windows API.
Sample code excerpt to read a string value from the Windows Registry using the native Windows API.

And this is just the part to query the destination string length. Then, you need to allocate a string object with proper size (and pay attention to proper size-in-bytes-to-size-in-wchar_ts conversion!), and after that you can finally read the actual string value into the local string object.

That’s definitely a lot of bug-prone C++ code, and this is just to query a string value!

Moreover, in modern C++ code you should prefer using nice higher-level resource manager classes with automatic resource cleanup, instead of raw HKEY handles.

Fortunately, it’s possible to hide that kind of complex and bug-prone code in a nice C++ library, that offers a much more programmer-friendly interface. This is basically what my C++ WinReg library does.

You can query a string value with just one simple line of C++ code using WinReg.
You can query a string value with just one simple line of C++ code using WinReg.

WinReg is an open-source C++ library, available on GitHub. For the sake of convenience, I packaged and distribute it as a header-only library, which is also available via the vcpkg package manager.

If you need to access the Windows Registry from your C++ code, you may want to give C++ WinReg a try.

 

New Pluralsight Course on C++ Standard Library Associative Containers

Happy Pi Day!

My new Pluralsight course on C++ Standard Library Associative Containers is live!

In this course, you’ll learn with a combination of slides and demo code, how to use associative containers like std::set, std::map, and std::unordered_map.

This is a follow up course of my previous course, which I encourage you to watch before this one.

Starting from this course page, you can freely play the course overview, and read a more detailed course description and the table of content.

Comparing the performance of std::unordered_map vs. std::map.
Comparing the performance of std::unordered_map vs. std::map.
Analyzing a subtle bug when working with std::map.
Analyzing a subtle bug when working with std::map.

These are some feedback notes from my reviewers:

Nice use of the PowerPoint slides and Camtasia callouts to keep the learners focused and engaged. [Peer Review]

Enjoyable clip of std::map string to string dictionary translation. [Peer Review]

Overall, a strong module that’s well-explained, approachable and professionally polished. Looking forward to more! [Peer Review]

The content is logically sequenced, building on concepts as we go. The clips are nice and short, which makes it easy to move through and absorb the content. You also do a great job transitioning across the clips; there’s a cohesive flow to the module. [Peer Review]

I’m glad you showed this error, explained why it’s happening, and how to fix it. It’s a good opportunity to reiterate learnings from earlier in the module, and also seems like a common gotcha. [Peer Review]

Happy learning!

 

New Pluralsight Course on C++ Standard Library Containers

My new Pluralsight course on C++ Standard Library Containers is live!

In this course, you’ll learn how to use some important containers implemented in the C++ Standard Library, with a combination of theoretical introduction using slides, and practical C++ implementation code, including analyzing and fixing some common bugs.

Comparing the memory layout of std::list vs. std::vector.
Comparing the memory layout of std::list vs. std::vector.

C++ Standard Library implementations offer high-quality well-tested and highly-optimized standard containers, that are very powerful tools when developing software written in C++.

In particular, I’ll discuss std::vector (which is a Standard Library workhorse), std::array, and std::list, including how to use them, discussing their pros and cons, and giving some guidance on picking one or the other, based on the problem at hand. Other containers (e.g. std::map) will be the topic of follow-up courses.

No prior knowledge of C++ Standard Library containers is required. You only need a basic knowledge of C++ language features.

Working on the implementation of a case-insensitive string search.
Working on the implementation of a case-insensitive string search.

Containers and algorithms are kind of like “bread and butter”, so in this course you’ll also learn about the C++ Standard Library design based on the teamwork between containers, iterators and algorithms, and you’ll see how to perform important operations on containers leveraging some useful algorithms already implemented in the C++ Standard Library.

Explaining the erase-remove idiom.
Explaining the erase-remove idiom.

Note that this course is both theory and practice! In fact, I’ll show practical demo code, and I’ll also discuss some bugs that are especially common for those who are just starting to learn the C++ Standard Library’s containers.

Analyzing a subtle bug when working with std::list.
Analyzing a subtle bug when working with std::list.

These are some feedback notes from my reviewers:

The narration is clear, animated, and engaging. The visuals are particularly helpful. [Peer Review]

You do a particularly good job clearly stating the problem here (and elsewhere) so that the solution, when it comes, makes sense and fits nicely. [Peer Review]

Great simple example of undefined behavior to reinforce the concepts you’ve introduced as well as a bonus of uncovering a security issue. [Peer Review]

Very nice module with good examples. Also excellent visuals when describing list, vectors and the various operations. [Peer Review]

Very nice discussion of the trade-offs between a linked list and a vector [Peer Review]

Nice use of a bug to teach a key concept [Peer Review]

 

Starting from this course page, you can freely play the course overview, and read a more detailed course description and the table of content.

Let me also express my gratitude to all the Pluralsight persons involved in the production of this course: It’s always a pleasure to work with you all!

I hope you’ll enjoy watching this course!

 

Printing UTF-8 Text to the Windows Console: Sample Code

In a previous blog post, you saw that to print some UTF-8-encoded text to the Windows console, you first have to convert it to UTF-16.

In fact, calling _setmode to change stdout to _O_U8TEXT, and then trying to print UTF-8-encoded text with cout, resulted in a debug assertion failure in the VC++ runtime library. (Please take a look at the aforementioned blog post for more details.)

That blog post lacked some compilable demo code showing the solution, though. So, here you are:

// Test printing UTF-8-encoded text to the Windows console

#include "UnicodeConv.hpp"  // My Unicode conversion helpers

#include <fcntl.h>
#include <io.h>
#include <stdint.h>
#include <iostream>
#include <string>

int main()
{
    // Change stdout to Unicode UTF-16.
    //
    // Note: _O_U8TEXT doesn't seem to work, e.g.:
    // https://blogs.msmvps.com/gdicanio/2017/08/22/printing-utf-8-text-to-the-windows-console/
    //
    _setmode(_fileno(stdout), _O_U16TEXT);


    // Japanese name for Japan, encoded in UTF-8
    uint8_t utf8[] = {
        0xE6, 0x97, 0xA5, // U+65E5
        0xE6, 0x9C, 0xAC, // U+672C
        0x00
    };
    std::string japan(reinterpret_cast<const char*>(utf8));

    // Print UTF-16-encoded text
    std::wcout << Utf16FromUtf8("Japan") << L"\n\n";
    std::wcout << Utf16FromUtf8(japan)   << L'\n';
}

This is the output:

Unicode UTF-8 text converted to UTF-16 and printed out to the Windows console

All right.

Note also that I set the Windows console font to MS Gothic to be able to correctly render the Japanese kanjis.

The compilable C++ source code, including the implementation of the Utf16FromUtf8 Unicode conversion helper function, can be found here on GitHub.

 

C++ WinReg Update

The Windows Registry native C API is very low-level and hard to use.

A while back I developed some convenient higher-level C++ wrappers, that should make Windows Registry programming easier and more fun. You can find them on GitHub.

Just to give you a taste of this C++ WinReg library, you can simply open a registry key with code like this:

RegKey key{ HKEY_CURRENT_USER, L"SOFTWARE\\MyKey" };

And you can read registry values like that:

DWORD dw = key.GetDwordValue(L"MagicCode");
wstring s = key.GetStringValue(L"ReadMe");

Enumerating values under a given key is as easy as:

auto values = key.EnumValues();

Error management is performed using C++ exceptions (instead of “raw” error codes like in the native C API).

You can find more info in the README file.

I haven’t touched that project in a few months (being very busy), but yesterday I accepted an external contribution and merged a pull request adding a DeleteTree feature.

I take this occasion to thank everyone who showed interest and appreciation for this project.

Happy coding!

 

New Pluralsight Course: Introduction to Data Structures and Algorithms in C++

A new course of mine was published in the Pluralsight library: Introduction to Data Structures and Algorithms in C++.

In this course, you’ll learn how to implement some fundamental data structures and algorithms in C++ from scratch, with a combination of theoretical introduction using slides, and practical C++ implementation code.

Introducing the stack with an interesting metaphor

No prior data structure or algorithm theory knowledge is required. You only need a basic knowledge of C++ language features (please watch the “Prerequisites” clip in the first module for more details about that).

Explaining linear search using slides

During this course journey, you’ll also learn some practical C++ coding techniques (ranging from move semantic optimization, to proper safe array copying techniques, insertion operator overloading, etc.) that you’ll be able to use in your own C++ projects, as well.

So, this course is both theory and practice!

Spotting a subtle bug

Here’s just a couple of feedback notes from my reviewers:

The callouts are helpful and keep the demo engaging as you explain the code. [Peer Review]

To say that this is an excellent explanation of Big-O notation would be an understatement. The way you illustrate and explain it is far better than the way it was taught to me in college! [Peer Review]

Big-O doesn’t have to be boring!

Starting from this course page, you can freely play the course overview, and read a more detailed course description and table of content.

I hope you’ll enjoy watching this course!

 

C++ String Guidance

Last time, I enumerated a few types of strings available in C++.

These days, I’d suggest as the default option for cross-platform standard C++ code to use std::string, storing UTF-8-encoded text inside it. Note that pure ASCII is a proper subset of UTF-8, so storing pure ASCII text in std::string objects is just fine.

In addition, for those platform-specific sections of C++ code, I’d suggest using whatever string class and encoding are typical and “natural” for that platform. For example, at the Windows API boundary, use the UTF-16 encoding, and the std::wstring class in C++ code that doesn’t use ATL or MFC.

In addition, in C++ Windows-specific code that already uses ATL or MFC, another option is to use CString (or the explicit CStringW) enabling Visual Studio Unicode builds (“Configuration Properties” | “General” | “Character Set”: “Use Unicode Character Set”, which has been the default since probably Visual Studio 2005).

On the other hand, Qt-based C++ code can use the QString class, and so on.