c++ string 转GUID及反转


#include "stdafx.h"
#include <string>
#include <windows.h>

using namespace std;

#define CONVERT_STR_2_GUID(cstr, stGuid) do\
{\
    swscanf_s((const wchar_t*)cstr, L"{%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x}",\
    &(stGuid.Data1),&(stGuid.Data2),&(stGuid.Data3),\
    &(stGuid.Data4[0]),&(stGuid.Data4[1]),&(stGuid.Data4[2]),&(stGuid.Data4[3]),\
    &(stGuid.Data4[4]),&(stGuid.Data4[5]),&(stGuid.Data4[6]),&(stGuid.Data4[7]));\
}while(0);

int _tmain(int argc, _TCHAR* argv[])
{
    const wstring strGuid = L"{9245fe4a-d402-451c-b9ed-9c1a04247482}";
    GUID stGuid = {0};

    CONVERT_STR_2_GUID(strGuid.c_str(), stGuid);

    wprintf_s(L"%s\r\n",strGuid.c_str());
    wprintf_s(L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", stGuid.Data1,stGuid.Data2,stGuid.Data3,
        stGuid.Data4[0],stGuid.Data4[1],stGuid.Data4[2],stGuid.Data4[3],
        stGuid.Data4[4],stGuid.Data4[5],stGuid.Data4[6],stGuid.Data4[7]);

    return 0;
}

上面这段程序能看出问题来么? 看出来的兄弟可以在下面指出来!

反正在vs2012及vs2013环境中验证是有问题的。如GUID {9245fe4a-d402-451c-b9ed-9c1a04247482},报下面现象:

---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Debug Error!

Program: D:\CPP_Pro\GUIDTest\Debug\GUIDTest.exe
Module: D:\CPP_Pro\GUIDTest\Debug\GUIDTest.exe
File:

Run-Time Check Failure #2 - Stack around the variable 'stGuid' was corrupted.

(Press Retry to debug the application)

---------------------------
中止(A) 重试(R) 忽略(I)
---------------------------

暂时记在这,其实还有其它方法可以实现,可以避免上面出错, 如下:

#include "stdafx.h"
#include <string>
#include <windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	const wstring strGuid = L"{9245fe4a-d402-451c-b9ed-9c1a04247482}";
	GUID stGuid = {0};

	CLSIDFromString((LPCOLESTR)strGuid.c_str(), (LPCLSID)&stGuid);

	wprintf_s(L"%s\r\n",strGuid.c_str());
	wprintf_s(L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", stGuid.Data1,stGuid.Data2,stGuid.Data3,
		stGuid.Data4[0],stGuid.Data4[1],stGuid.Data4[2],stGuid.Data4[3],
		stGuid.Data4[4],stGuid.Data4[5],stGuid.Data4[6],stGuid.Data4[7]);

	return 0;
}

反转就更容易了,可以用sprintf之类的,也可以用StringFromCLSID

参考:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms680589(v=vs.85).aspx


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM