从std::string转换为String^

7

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

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

3
我认为你需要另一个标签,因为在C++中String^并不太有意义。 - juanchopanza
这是托管C++语法。而且你的函数甚至都不合法,没有标识符。 - Aesthete
问题在于这个函数被用来将一个值从C++转换到C#。我的意思是,这个函数是由C#程序调用的。 - Moti
@juanchopanza,这也存在于WinRT中,可能应该在std::string上调用.c_str()。 - johnathan
@johnathon - 是的,我现在正在阅读所有相关内容。我已经更改了问题的标签,但我会让原帖发布者或其他人将其更改为winRT / CLI - 因为我不确定它应该是什么。 - Aesthete
显示剩余4条评论
3个回答

15

11

通过谷歌搜索发现 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;
}

请参阅Marshaling概述


1
这个不再编译。 - DKS

2
据我所知,至少使用marshal_as方法(不确定gcnew String)会导致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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接