Vulkan is a C API and as such inherits all common pitfalls of using a general C programming library. The motivation of a low-level Vulkan C++ API is to avoid these common pitfalls by applying commonly known C++ features while keeping the overall structure of a Vulkan program and preserving the full freedom it provides as low-level graphics API. An additional guideline we followed was not to introduce additional runtime overhead by providing a header-only library with inline functions.

Have a look at the following piece of code which creates a VkImage:

VkImageCreateInfo ci;
ci.pNext = nullptr;
ci.flags = … some flags...;
ci.imageType = VK_IMAGE_TYPET_2D;
ci.format = VK_FORMAT_R8G8B8A8_UNORM;
ci.extent = VkExtent3D { width, height, 1 };
ci.mipLevels = 1;
ci.arrayLayers = 1;
ci.samples = VK_SAMPLE_COUNT_1_BIT;
ci.queueFamilyIndexCount = 0;
ci.pQueueFamilyIndices = 0;
vkCreateImage(device, &ci, allocator, &image));

There may be some issues than can happen when filling the structure which cannot be caught at compile time:

  • initialization of ci.sType using wrong enum values
  • uninitialized data fields (e.g. missing initialization of ci.mipLevels)
  • use of invalid bits for ci.flags (no type-safety for bits)
  • use of incorrect enums for fields (no type-safety for enums)

These initializations will most likely show up as random runtime errors, which usually are nasty and time-consuming to debug. Our auto-generated, C++ 11-conform layer uses commonly known C++ features like implicit initialization through constructors to avoid incorrect or missing initializations and introduces type-safety with scoped enums to turn explicit initialization errors into compile errors.

Following is a list of features and conventions introduced by our Vulkan C++ layer:

  • Works along the official C version of the API
  • Defines all symbols within the ‘vk’ namespace and to avoid redundancy the vk/Vk/VK_ prefixes have been removed from all symbols, i.e. vk::commandBindPipeline for vkCommandBindPipeline.
  • Camel case syntax with an ‘e’ prefix has been introduced for all enums, i.e. vk::ImageType::e2D (the prefix was a compromise, more about that later)
  • Removes the ‘BIT’ suffix from all flag related enums, i.e. vk::ImageUsage::eColorAttachment.
  • Introduces constructors for all structs, which by default set the appropriate sType and all other values to zero.
  • Encapsulates member variables of the structs with getter and setter functions, i.e. ci.imageType() to get a value and ci.imageType(vk::ImageType::e2D) to set a value.

With those changes applied, the updated code snippet looks like this:

vk::ImageCreateInfo ci;
ci.flags(...some flags…);
ci.extent(vk::Extent3D { width, height, 1 });
  // ci.queueFamilyIndexCount(0)	// no need to set, already initialized
  // ci.pQueueFamilyIndices(0)	// no need to set, already initialized
vk::createImage(device, &ci, allocator, &image)); 

Which is a total of 13 lines of code, versus 17 lines for the C version. In addition, this code is more robust as described above.

Type-safe Enums

Splitting up the C enums into a namespace and scoped enums resulted in two compilation issues. First some enums started with a digit like vk::ImageType::1D which resulted in a compilation error. Second, there’s the risk that upper symbols like

vk::CompositeAlphaFlagBitsKHR::OPAQUE do clash with preprocessor defines. In the given example OPAQUE has been defined in win32gdi.h resulting a compilation error.

To overcome those two issues the symbols have been converted to camel case and the prefix ‘e’ has been added so that each enum starts with a letter.

Improvements to Bit Flags

After those changes the code might look more familiar to C++ developers, but there is still no gain with regards to safety. With C++ features available we replaced all Vulkan enums with scoped enums to achieve type safety which already uncovered a few small issues in our code. The good thing with scoped enums is that there is no implicit casts to integer types anymore. The downside is that OR’ing the bits for the flags does not work anymore without an explicit cast. As a solution to this problem we have introduced a new vk::Flags template which is used for all flags. This class supports the standard operations one usually needs on bitmasks like &=, |=, & and |. Except for the initialization with 0, which is being replaced by the default constructor, the vk::Flags class works exactly like a normal bitmask with the improvement that it is impossible to set bits not specified by the corresponding enum. To generate a bit mask with two bits set write:

ci.usage = vk::ImageUsage::eColorAttachment | vk::ImageUsage::eStorage;

By adding the scoped enums and vk::Flags the C++ API provides type safety for all enums and flags which is a big improvement. This leaves the remaining issue that the compiler might not detect uninitialized fields in structs. As a solution we’ve added constructors to all structs which accept all values defined by the corresponding struct.

vk::ImageCreateInfo ci(
  some flags, vk::ImageType::e2D, vk::Format::eR8G8B8A8Unorm,
  vk::Extent3D { width, height, 1 }, 1, 1,
  vk::SampleCount::e1, vk::ImageTiling::eOptimal,
  vk::ImageUsage::eColorAttachment, vk::SharingMode::eExclusive,
  0, 0, vk::ImageLayout::eUndefined);

Alternative Initialization of Structs

Another nice feature of those constructors is that sType is being initialized internally and thus is always correct.

Finally, we’ve added a default constructor to each struct which initializes all values to 0 to allow setting the values with the named parameter idiom which is similar to the designated initializer list of C99.

vk::ImageCreateInfo ci = vk::ImageCreateInfo()
  .flags(...some flags…)
  .extent(vk::Extent3D { width, height, 1 })
  // .queueFamilyIndexCount(0)	// no need to set, already initialized
  // .pQueueFamilyIndices(0)	// no need to set, already initialized
vk::createImage(device, &ci, allocator, &image));

Enhancements beyond the API

While mapping the Vulkan API to C++ without adding new functions is already a big help, one can do even more by adding new functionality. For example several C++ developers tend to use std::string and std::vector in their code, therefore we have added some more optional convenience features:

  • Use std::string instead of const char * for strings
  • Use std::vector instead of (count, ptr) for sized arrays
  • Throw exceptions (Work in Progress)
  • Return handles/vectors where applicable, i.e. for the create* functions

As example let’s examine the device extension property enumeration in Vulkan:

    uint32_t count;
layerName.c_str(), &count, nullptr));

    std::vector <vk::ExtensionProperties> properties(count); 
layerName.c_str(), &count,;

Luckily the official Khronos-provided vk.xml has enough information to figure out which pair of values represents a sized array or strings, so that it is possible to generate a function which allows you to write the following line of code instead:

  std::vector<ExtensionProperties> properties = 
 vk::enumerateDeviceExtensionProperties(physicalDevice, layerName); 

If you’re interested in the project you can find it at:

Feel free to fork the code-generator and customize it for your own needs and let us know what other features you are interested in.

Written by: Markus Tavenrath & Andreas Süßenbach