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

I think CoCreateGuid is what you're after. Example:

GUID gidReference;
HRESULT hCreateGuid = CoCreateGuid( &gidReference );

UuidCreate() in Win32 API has exactly the same effect. However you need to pass an address of the variable that will receive the generated value:

UUID newId;
UuidCreate( &newId );

I believe Guid.NewGuid() simply maps onto it inside the .NET runtime.


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

// For UUID
#include <Rpc.h>
#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