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

前端 未结 7 1496
栀梦
栀梦 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:38

    Here's a snippet of code to get the resulting string value of the generated GUID:

    // For UUID
    #include 
    #pragma comment(lib, "Rpcrt4.lib")
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        // Create a new uuid
        UUID uuid;
        RPC_STATUS ret_val = ::UuidCreate(&uuid);
    
        if (ret_val == RPC_S_OK)
        {
            // convert UUID to LPWSTR
            WCHAR* wszUuid = NULL;
            ::UuidToStringW(&uuid, (RPC_WSTR*)&wszUuid);
            if (wszUuid != NULL)
            {
                //TODO: do something with wszUuid
    
                // free up the allocated string
                ::RpcStringFreeW((RPC_WSTR*)&wszUuid);
                wszUuid = NULL;
            }
            else
            {
                //TODO: uh oh, couldn't convert the GUID to string (a result of not enough free memory)
            }
        }
        else
        {
            //TODO: uh oh, couldn't create the GUID, handle this however you need to
        }
    
        return 0;
    }
    

    API reference:

    • UuidCreate
    • UuidToString
    • RpcStringFree

提交回复
热议问题