c++ - 将字符串转换为 GUID 不会给出正确的结果

标签 c++ visual-studio boost boost-propertytree

在我的程序中,我需要读取存储在 xml 文件中的 guid 值。这是 xml 文件的样子。

<data>
 <id>3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE</id>
</data>

我的程序需要读取 GUID 类型变量中的这个值。以下是我对此的看法。

#include "stdafx.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <iostream>
#include <Windows.h>
namespace pt = boost::property_tree;
#pragma comment(lib, "rpcrt4.lib") 
int main()
{
    pt::ptree tree;
    std::string filename = "data.xml";

    pt::read_xml(filename, tree);

    std::string idStr = tree.get<std::string>("data.id");
    std::cout << "id as string = " << idStr << std::endl;
    GUID idAsGuid;

    auto res = UuidFromStringW((RPC_WSTR)idStr.c_str(), &idAsGuid);
    if (FAILED(res))
    {
        std::wcerr << L"Conversion failed with error: 0x" << std::hex << res << std::endl;
    }

   return 0;
}

变量 idStr 获得正确的值,但 idAsGuid 变量(即 GUID 类型)获得不正确的值(类似于 CCCCC-CCCC-CCCC-CCCCCCCCCCCCCC)。我在这里错了什么?

最佳答案

std::string::c_str() 返回一个 const char* 指针,您将其类型转换为 RPC_WSTR,又名非常量 unsigned short*。那个 Actor 永远不会奏效。至少,您需要先将 std::stringconvert 为 UTF-16 编码的 std::wstring,例如:

#include <locale>
#include <codecvt>

std::wstring widStr = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>{}.from_bytes(idStr);

auto res = UuidFromStringW(reinterpret_cast<RPC_WSTR>(const_cast<wchar_t*>(widStr.c_str())), &idAsGuid);
// or:
// auto res = UuidFromStringW(reinterpret_cast<RPC_WSTR>(&widStr[0]), &idAsGuid);

否则,请改用 UuidFromStringA(),但请注意 RPC_CSTR 被定义为 非常量 unsigned char*,所以你仍然需要类似的转换:

auto res = UuidFromStringA(reinterpret_cast<RPC_CSTR>(const_cast<char*>(idStr.c_str())), &idAsGuid);
// or:
// auto res = UuidFromStringA(reinterpret_cast<RPC_CSTR>(&idStr[0]), &idAsGuid);

话虽如此,请考虑改用 GUIDFromStringA(),它不需要任何转换或转换:

auto res = GUIDFromStringA(idStr.c_str(), &idAsGuid);

不过,您可能必须向 guid 字符串添加大括号:

auto res = GUIDFromStringA(("{" + idStr + "}").c_str(), &idAsGuid);

否则,只需手动解析 guid 字符串,例如使用 std::istringstreamstd::regexstd::sscanf()

关于c++ - 将字符串转换为 GUID 不会给出正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51546551/

相关文章:

c++ - 升级到较新版本后 boost fusion/mpl 问题

c++ - enable_if 类型的大小未知

c++ - 这个可变参数模板代码有什么作用?

c++ - extern "C"仅在函数声明中需要吗?

c++ - 如何创建一个用户可以在菜单更改之间不断添加值的 vector ?

angularjs - 在 Visual Studio 2015 中将 TypeScript 编译成 Javascript

c# - .Net 内存跟踪中的 "TargetCore"是什么?

wpf - 限制 slider 文本框小数位数

c++ - 如何在 C++ 中填充数据或访问 3 维 vector

c++ - 如果启用了 BOOST,如何检查我的代码?