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

前端 未结 7 1498
栀梦
栀梦 2021-01-31 14:04

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++ vers

7条回答
  •  面向向阳花
    2021-01-31 14:43

    To get in guid in std::string on Windows

    #include 
    #include 
    
    std::string getGUID()
    {
        std::string result{};
        GUID guid;
    
        if (S_OK == CoCreateGuid(&guid))
        {
            std::array 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;
    } 
    

提交回复
热议问题