Search code examples
c++guid

Print a GUID variable


I have a GUID variable and I want to write inside a text file its value. GUID definition is:

typedef struct _GUID {          // size is 16
    DWORD Data1;
    WORD   Data2;
    WORD   Data3;
    BYTE  Data4[8];
} GUID;

But I want to write its value like:

CA04046D-0000-0000-0000-504944564944

I observed that:

  • Data1 holds the decimal value for CA04046D
  • Data2 holds the decimal value for 0
  • Data3 holds the decimal value for next 0

But what about the others?

I have to interpret myself this values in order to get that output or is there a more direct method to print such a variable?


Solution

  • Use the StringFromCLSID function to convert it to a string

    e.g.:

    GUID guid;
    CoCreateGuid(&guid);
    
    OLECHAR* guidString;
    StringFromCLSID(guid, &guidString);
    
    // use guidString...
    
    // ensure memory is freed
    ::CoTaskMemFree(guidString);
    

    Also see the MSDN definition of a GUID for a description of data4, which is an array containing the last 8 bytes of the GUID