What's the C++ version of Guid.NewGuid()?

Viewed 76847

I need to create a GUID in an unmanaged windows C++ project. I'm used to C#, where I'd use Guid.NewGuid(). What's the (unmanaged windows) C++ version?

7 Answers

In the new WinRT api you can use winrt::Windows::Foundation::GuidHelper::CreateNewGuid() which returns a struct of winrt::guid type. You can later pass it to winrt::to_hstring to get struct of winrt::hstring type, then pass it to winrt::to_string to get std::string type.

To get in guid in std::string on Windows

#include <Windows.h>
#include <array>

std::string getGUID()
{
    std::string result{};
    GUID guid;

    if (S_OK == CoCreateGuid(&guid))
    {
        std::array<char, 36> buffer{};   //32 characters of guid + 4 '-' in-between

        snprintf(buffer.data(), buffer.size(), "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
        result = std::string(buffer.data());
    }

    return result;
} 
Related