问题描述
我正在使用C中的Win32 API,并且需要将GUID结构转换为LPCSTR.我是Win32的新手,没有找到太多有关此类转换的信息.
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.
我确实设法使用StringFromGUID2函数将GUID转换为OLECHAR(请参见下面的代码片段),但是在进一步转换为LPSCSTR时遇到了麻烦.我不太确定我会朝着OLECHAR的正确方向前进,但目前看来这是合乎逻辑的事情.
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));
推荐答案
操作系统不支持直接将GUID格式化为Ansi字符串.您可以先将其格式化为Unicode字符串,然后再将其转换为Ansi:
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);
或者您可以使用 sprintf()
或类似函数手动格式化Ansi字符串:
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]);
这篇关于将GUID结构转换为LPCSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!