【问题标题】:C++/CX : Convert std::string to Platform::String^C++/CX : 将 std::string 转换为 Platform::String^
【发布时间】:2016-01-04 15:02:42
【问题描述】:

有没有一种简单的方法(一行代码会很酷)在 C++/CX 中将 à std::string 转换为 Platform::String^ ?

我找到了how to do it the other way(String^ to string) 但没有找到这个。

类似:

std::string str = "Hello World";
Platform::String^ p_str = convertFromString(str);

(在示例中它毫无意义,但是当您在 c++ 中使用 std::string 并且您想将其发送到某些 C# 代码时更有意义)

【问题讨论】:

  • 您总是可以尝试使用 charArray 在它们之间进行转换?
  • 叹息,22 年的 Unicode 并没有阻止这样的问题。您已经知道如何从该帖子转换为 std::wstring 。然后是单线,ref new String(wide.c_str())
  • 我可以制作其他东西(使用 char * 等...),但我想知道是否有一种好的/简单的方法

标签: c# c++ c++-cx windows-rt


【解决方案1】:

这个方法适合我

Platform::String ^ convertFromString(const std::string & input)
{
    std::wstring w_str = std::wstring(input.begin(), input.end());
    const wchar_t* w_chars = w_str.c_str();

    return (ref new Platform::String(w_chars));
}

【讨论】:

  • 为我工作,回报略有变化return (ref new Platform::String(w_chars, w_str.length()));
【解决方案2】:

目前无法直接将std::string 转换为std::wstring

但是,我们可以进行从std::stringstd::wstring 的迂回转换,然后从std::wstringPlatform::String,如下所示:

#include <locale>
#include <codecvt>
#include <string>

Platform::String^ stringToPlatformString(std::string inputString) {
  std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  std::wstring intermediateForm = converter.from_bytes(inputString);
  Platform::String^ retVal = ref new Platform::String(intermediateForm.c_str());

  return retVal;
}

有关std::stringstd::wstring 转换的更多信息,请参阅this question

【讨论】:

    【解决方案3】:

    如果您在转换中不喜欢被限制为基本拉丁语(Unicode 块),就像在我的情况下需要 æøå,这样可以:

    #include <sstream>
    
    Platform::String^ StdStringToPlatformString(std::string str)
    {
       std::wstringstream wss;
       wss << str.c_str();
       return ref new Platform::String(wss.str().c_str());
    }
    

    【讨论】:

      【解决方案4】:

      所以基本上答案是否定的:它更复杂。您需要先在 std::wstring 中转换 std::string,然后使用 user1 的答案(将 std::wstring 转换为 Platform::String^)。 对于字符串到 wstring 的转换,您可以检查 this other question(这对我不起作用,但无论如何,我只需要进行更深入的转换)。

      (我已经放了一些代码,但被告知这样做很糟糕,因为我只是为了调试而这样做,无论如何我都会删除它我不在乎,但我不想给出反建议所以我删除了那个代码)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-28
        相关资源
        最近更新 更多