Convert GUID structure to LPCSTR

I work with the Win32 API in C and I need to convert the GUID structure to LPCSTR. I am relatively new to Win32 and have not found much information about this type of conversion.

I managed to convert the GUID to OLECHAR using the StringFromGUID2 function (see the code snippet below), but got stuck in further converting to LPSCSTR. I'm not sure I'm heading in the right direction with OLECHAR, but at the moment it seems logical.

GUID guid; OLECHAR wszGuid[40] = {0}; OLECHAR szGuid[40]={0}; LPCSTR lpcGuid; CoCreateGuid(&guid); StringFromGUID2(&guid, wszGuid, _countof(wszGuid)); 
+4
source share
1 answer

The OS does not support GUID formatting as Ansi strings directly. You can format it first as a Unicode string and then convert to Ansi:

 GUID guid = {0}; wchar_t szGuidW[40] = {0}; char szGuidA[40] = {0}; CoCreateGuid(&guid); StringFromGUID2(&guid, szGuidW, 40); WideCharToMultiByte(CP_ACP, 0, szGuidW, -1, szGuidA, 40, NULL, NULL); 

Or you can use sprintf() or a similar function to format the Ansi string manually:

 GUID guid = {0}; char szGuid[40]={0}; CoCreateGuid(&guid); sprintf(szGuid, "{%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]); 
+10
source

Source: https://habr.com/ru/post/1499989/


All Articles