5

I am working with Win32 API in C and have a need to convert a GUID structure into LPCSTR. I am relatively new to Win32 and didn't find much information around this type of conversion.

I did manage to convert GUID to OLECHAR using StringFromGUID2 function (see code fragment below) but stuck on further conversion to LPSCSTR. I am not too sure I am heading in the correct direction with OLECHAR but at the moment it seems logical thing to do.

GUID guid;
OLECHAR wszGuid[40] = {0};
OLECHAR szGuid[40]={0};
LPCSTR lpcGuid;
CoCreateGuid(&guid);
StringFromGUID2(&guid, wszGuid, _countof(wszGuid));
user2177565
  • 89
  • 1
  • 2
  • 8

1 Answers1

16

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

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 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]);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks Remy. In your 2nd approach you used sprintf function compare to the two function calls (StringFromGUID2 and WideCharToMultiByte) in the 1st approach. From surface of it 2nd approach seems more tighter and concise which make me believe it may be faster too but I am not sure. Any thoughts on that? – user2177565 Sep 02 '13 at 05:55
  • I don't know, but I bet the second is slower because it is not specialized, the `sprintf` has to parse the input string and decide what to do with the additional arguments, but the other is exactly purpose built. -- The fastest would be to build a new purpose built function using the logic evident in the 2nd approach, that translates the GUID to ANSI directly. – Motomotes Oct 13 '16 at 18:05