【问题标题】:convert from std::string to String^从 std::string 转换为 String^
【发布时间】:2012-12-05 07:19:58
【问题描述】:

我在 C++ 中有一个函数,它有一个 std::string 类型的值,并且想将它转换为 String^。

void(String ^outValue)
{
   std::string str("Hello World");
   outValue = str;
}

【问题讨论】:

  • 我认为你需要另一个标签,因为String^ 在 C++ 中没有多大意义。
  • 这是托管的 c++ 语法。而且您的功能甚至无效,没有标识符。
  • 问题是这个函数用于将值从C++转换为C#/我的意思是这个函数是由C#程序调用的
  • @juanchopanza 它也存在于 WinRT 中,可能应该调用 .c_str();在 std::string
  • @JoachimPileborg 好吧,我敢肯定有一个标签!

标签: string c++-cli managed-c++


【解决方案1】:

谷歌搜索显示marshal_as(未经测试):

// marshal_as_test.cpp
// compile with: /clr
#include <stdlib.h>
#include <string>
#include <msclr\marshal_cppstd.h>

using namespace System;
using namespace msclr::interop;

int main() {
   std::string message = "Test String to Marshal";
   String^ result;
   result = marshal_as<String^>( message );
   return 0;
}

另见Overview of Marshaling

【讨论】:

    【解决方案2】:

    来自 MSDN:

    #include <string>
    #include <iostream>
    using namespace System;
    using namespace std;
    
    int main() {
       string str = "test";
       String^ newSystemString = gcnew String(str.c_str());
    }
    

    http://msdn.microsoft.com/en-us/library/ms235219.aspx

    【讨论】:

      【解决方案3】:

      据我所知,至少 marshal_as 方法(不确定 gcnew 字符串)会导致 std::string 中的非 ASCII UTF-8 字符被破坏。

      根据我在 https://bytes.com/topic/c-sharp/answers/725734-utf-8-std-string-system-string 上找到的内容,我构建了这个解决方案,至少在德语变音符号上似乎对我有用:

      System::String^ StdStringToUTF16(std::string s)
      {
      
       cli::array<System::Byte>^ a = gcnew cli::array<System::Byte>(s.length());
       int i = s.length();
       while (i-- > 0)
       {
          a[i] = s[i];
       }
      
       return System::Text::Encoding::UTF8->GetString(a);
      }
      

      【讨论】:

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