How to initialize a constant CLSID

2019-06-15 07:10发布

问题:

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?

回答1:

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.



回答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}");
}