13

A class ID (GUID) is generally specified with a sequence of hex numbers separated by dashes, e.g. {557cf406-1a04-11d3-9a73-0000f81ef32e}. This is not a literal that can be used to initialize a CLSID structure directly.

I've discovered two ways to initialize the structure, but they're both kind of awkward. The first doesn't allow it to be declared const and must be done at run time, while the second requires extensive reformatting of the hex constants.

CLSID clsid1;
CLSIDFromString(CComBSTR("{557cf406-1a04-11d3-9a73-0000f81ef32e}"), &clsid1);

const CLSID clsid2 = { 0x557cf406, 0x1a04, 0x11d3, { 0x9a,0x73,0x00,0x00,0xf8,0x1e,0xf3,0x2e } };

I know that Visual Studio can generate one automatically if you have a type that's associated with a UUID, using the __uuidof operator. Is there a way to do it if you only have the hex string?

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Ahem: http://stackoverflow.com/questions/5345803/does-gdi-have-standard-image-encoder-clsids – i_am_jorf Apr 30 '15 at 19:17
  • 1
    You could always use a factory function that calls `CLSIDFromString` - something like `const CLSID clsid1 = GUIDFactoryFunc("{557cf406-1a04-11d3-9a73-0000f81ef32e}")` – Captain Obvlious Apr 30 '15 at 19:20
  • 1
    @i_am_jorf why do you think I'm asking the question? I need to use the answer from that question in a new program, and the code I wrote back then is a job ago and no longer available for reference. – Mark Ransom Apr 30 '15 at 19:20

2 Answers2

11

Static CLSID initialization from string (no runtime conversion helper needed):

class __declspec(uuid("{557cf406-1a04-11d3-9a73-0000f81ef32e}")) Foo;
static const CLSID CLSID_Foo = __uuidof(Foo);       
// ...
CComPtr<IUnknown> pUnknown;
pUnknown.CoCreateInstance(CLSID_Foo);

or simply direct use of __uuidof (compiler will treat the GUID value as a constant and generate minimal necessary code):

class __declspec(uuid("{557cf406-1a04-11d3-9a73-0000f81ef32e}")) Foo;
// ...
CComPtr<IUnknown> pUnknown;
pUnknown.CoCreateInstance(__uuidof(Foo));

It is not anything special: for example when type libraries are #imported, the same method is used to attach CLSIDs to coclass based types, and then additional CLSID_xxx identifiers might be generated if additionally requested.

Roman R.
  • 68,205
  • 6
  • 94
  • 158
2

Use a helper function to create the GUID.

#include <Windows.h>
#include <atlbase.h>

template<class S>
CLSID CreateGUID(const S& hexString)
{
    CLSID clsid;
    CLSIDFromString(CComBSTR(hexString), &clsid);

    return clsid;
}

int main()
{
    const CLSID clsid1 = CreateGUID("{557cf406-1a04-11d3-9a73-0000f81ef32e}");
    const CLSID clsid2 = CreateGUID(L"{557cf406-1a04-11d3-9a73-0000f81ef32e}");
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74