Skip to content

Commit b51e05e

Browse files
committed
Improve SetDebugUtilsObjectName
1 parent 2547e8e commit b51e05e

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

src/Tests.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ extern bool VK_KHR_maintenance5_enabled;
4242
extern PFN_vkGetBufferDeviceAddressKHR g_vkGetBufferDeviceAddressKHR;
4343
void BeginSingleTimeCommands();
4444
void EndSingleTimeCommands();
45-
void SetDebugUtilsObjectName(VkObjectType type, uint64_t handle, const char* name);
45+
void SetDebugUtilsObjectName(VkObjectType type, uint64_t handle, std::string);
4646

4747
#ifndef VMA_DEBUG_MARGIN
4848
#define VMA_DEBUG_MARGIN 0

src/VulkanSample.cpp

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include "Common.h"
2929
#include <atomic>
3030
#include <Shlwapi.h>
31+
#include <unordered_set>
3132

3233
#pragma comment(lib, "shlwapi.lib")
3334

@@ -261,16 +262,30 @@ struct CommandLineParameters
261262
}
262263
} g_CommandLineParameters;
263264

264-
void SetDebugUtilsObjectName(VkObjectType type, uint64_t handle, const char* name)
265+
void SetDebugUtilsObjectName(VkObjectType type, uint64_t handle, std::string name)
265266
{
266-
if(vkSetDebugUtilsObjectNameEXT_Func == nullptr)
267+
TEST(!name.empty());
268+
269+
// We must make sure the std::string we pass as name is still valid memory until the program ends.
270+
// Since Vulkan is a C-Style API, it only accepts const char* as pObjectName parameter.
271+
// Naming objects with unformatted names like "g_hTemporaryCommandBuffer" is no problem because
272+
// this string ends up in the read-only data section of the program. However, if we for example want to
273+
// name every item in a dynamic array of items (swapchain images for example), we can only use a std::string,
274+
// and we must make sure the object lifetime of that string does not end before it's read as pObjectName.
275+
// Therefore, we store the strings as a static unordered_set here just to be sure.
276+
// Do not use a std::vector because it would continue to grow, eventually running out of memory.
277+
static std::unordered_set<std::string> debug_names;
278+
auto result = debug_names.insert(name);
279+
const char* pObjectName = result.first->c_str();
280+
281+
if (vkSetDebugUtilsObjectNameEXT_Func == nullptr)
267282
return;
268283

269284
VkDebugUtilsObjectNameInfoEXT info = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };
270285
info.objectType = type;
271286
info.objectHandle = handle;
272-
info.pObjectName = name;
273-
vkSetDebugUtilsObjectNameEXT_Func(g_hDevice, &info);
287+
info.pObjectName = pObjectName;
288+
ERR_GUARD_VULKAN( vkSetDebugUtilsObjectNameEXT_Func(g_hDevice, &info) );
274289
}
275290

276291
void BeginSingleTimeCommands()

0 commit comments

Comments
 (0)