简体   繁体   English

如何在MFC中创建一个guid

[英]How can I create a guid in MFC

I need to be able to create guids on the fly. 我需要能够动态创建guid。 Is there a way to do that in MFC? 有没有办法在MFC中这样做? I see how to do it in .net, but we haven't gone there yet. 我知道如何在.net中做到这一点,但我们还没有去过那里。 If not, do you have pointers to some code I can use? 如果没有,你有指向我可以使用的一些代码的指针吗?

   //don't forget to add Rpcrt4.lib to your project

    CString m_ListID(L"error");
    RPC_WSTR guidStr;
    GUID guid;
    HRESULT hr = CoCreateGuid(&guid);
    if (hr == S_OK)
    {
        if(UuidToString(&guid, &guidStr) == RPC_S_OK)
        {
            m_ListID = (LPTSTR)guidStr;
            RpcStringFree(&guidStr);
        }
    }
GUID guid;
HRESULT hr = CoCreateGuid(&guid); 

// Convert the GUID to a string
_TUCHAR * guidStr;
UuidToString(&guid, &guidStr);

The application is responsible for calling RpcStringFree to deallocate the memory allocated for the string returned in the StringUuid parameter. 应用程序负责调用RpcStringFree来释放为StringUuid参数中返回的字符串分配的内存。

You can use the COM function CoCreateGuid, eg: 您可以使用COM函数CoCreateGuid,例如:

GUID guid;
HRESULT hr = CoCreateGuid(&guid);

Use the function UuidCreate to generate GUIDs : 使用函数UuidCreate生成GUID:

UUID generated;

if (::UuidCreate(&generated) != RPC_S_OK)
throw std::exception(...);

You can use this sample 您可以使用此示例

WCHAR       GuidText[250] ={0};
UUID        uuid;

CoCreateGuid (&uuid);
wsprintf(
        GuidText,
        L"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
        uuid.Data1,
        uuid.Data2,
        uuid.Data3,
        uuid.Data4[0], uuid.Data4[1],
        uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], uuid.Data4[5], uuid.Data4[6], uuid.Data4[7]
        );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM