How to initialize a constant CLSID

删除回忆录丶 提交于 2019-12-10 12:34:43

问题


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


来源:https://stackoverflow.com/questions/29975918/how-to-initialize-a-constant-clsid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!