Windows下C++生成全局唯一GUID

有些时候,需要使用全局唯一的GUID,其实在windows环境中,windows的API提供了生成GUID的函数,即CoCreateGuid,需要引入头文件objbase.h

具体的生成代码如下:
[php]
#include <objbase.h>
#include <stdio.h>

//–生成GUID
const char* GenerateGUID()
{
static char buf[64] = {0};
GUID guid;
if (S_OK == ::CoCreateGuid(&guid))
{
_snprintf(buf, sizeof(buf)
, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}"
, guid.Data1
, guid.Data2
, guid.Data3
, guid.Data4[0], guid.Data4[1]
, guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5]
, guid.Data4[6], guid.Data4[7]
);
}
return (const char*)buf;
}

int main()
{
//–COM
CoInitialize(NULL);

printf(GenerateGUID());
printf("\r\n");

//–COM
CoUninitialize();

return 0;
}
[/php]
运行结果如下图:
1

Comments are closed.