C++ 将 String^ 转换为 std::string(基本字符串)-> 错误。我怎样才能解决这个问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/775708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:13:18  来源:igfitidea点击:

Converting String^ to std::string (basic string) -> Error. How can I fix this?

c++stringstd

提问by Alejandro Perea

I try to convert a String^ to basic string...but I get the error after this code. What does it mean and how can I fix it? I need to input basic string into a class constructor. The string^ would not work.

我尝试将 String^ 转换为基本字符串...但在此代码后出现错误。这是什么意思,我该如何解决?我需要将基本字符串输入到类构造函数中。字符串^ 不起作用。

System::String^ temp = textBox1->Text;
string dummy = System::Convert::ToString(temp);
error C2440: 'initializing' : cannot convert from 'System::String ^' to 'std::basic_string'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits,
1>            _Ax=std::allocator
1>        ]
1>        No constructor could take the source type, or constructor overload resolution was ambiguous

回答by Filip Fr?cz

You need to marshal your string. The managed string sits somewhere on the managed heap (garbage collector is free to move it around).

你需要编组你的字符串。托管字符串位于托管堆的某处(垃圾收集器可以自由移动它)。

One way of getting the string to the native side is as follows:

获取字符串到本机端的一种方法如下:

using System::Runtime::InteropServices::Marshal;

char *pString = (char*)Marshal::StringToHGlobalAnsi(managedString);
std::string nativeString(pString); // make your std::string
Marshal::FreeHGlobal(pString);     // don't forget to clean up

If you are using Visual Studio 2008, you can take advantage of much nicer marshaling utilities. Check out this MSDN page.

如果您使用的是 Visual Studio 2008,则可以利用更好的封送实用程序。查看此 MSDN 页面

#include <msclr/marshal.h>
#include <msclr/marshal_cppstd.h>

using namespace msclr::interop;

std::string nativeString(marshal_as<std::string>(managedString));

回答by Alejandro Perea

I spend 11h to find a solution:

我花了 11h 找到了一个解决方案:

 #include <stdlib.h
 #include <string.h>
 #include <msclr\marshal_cppstd.h>
 //ListaQuad<int> prueba;
 //..
 using namespace msclr::interop;
 //..
 System::String^ clrString = (TextoDeBoton);
 std::string stdString = marshal_as<std::string>(clrString);  //String^ to std
 //System::String^ myString = marshal_as<System::String^>(MyBasicStirng);   //std to String^ (no lo he probado, pero sería algo así.)
 prueba.CopyInfo(stdString); //MyMethod
 //..
 //where, String^ = TextoDeBoton;
 //and, stdString = normal string;

回答by Corey Ross

You need to do two things to convert a System::Stringto a std::string:

您需要做两件事才能将 a 转换System::String为 a std::string

  • Marshal the memory from the managed heap an unmanaged one.
  • Convert your character encoding from a wide characters to (what looks like from your question) ansi characters.
  • 将托管堆中的内存编组为非托管堆。
  • 将您的字符编码从宽字符转换为(从您的问题中看起来像)ansi 字符。

One way, without having to worry about freeing any HGlobal memory is to define a method along the lines of:

一种无需担心释放任何 HGlobal 内存的方法是按照以下方式定义一个方法:

interior_ptr<unsigned char> GetAsciiString(System::String ^s)
{
    array<unsigned char> ^chars = System::Text::Encoding::ASCII->GetBytes(s);
    return &chars[0];
    // of course you'd want to do some error checking for string length, nulls, etc..
}

And you'd use it like:

你会像这样使用它:

// somewhere else...
{
    pin_ptr<unsigned char> pChars = GetAsciiString(textBox1->Text);
    std:string std_str(pChars); // I don't have my compiler in front of me, so you may need a (char*)pChars
}

This also lets you use the encoding of your choice (like utf-8 over ascii), but you may not really need this.

这也允许您使用您选择的编码(如 utf-8 而非 ascii),但您可能并不真正需要它。

回答by Pavel Mikhailov

May be, you will need inverse converting, from std::stringto String^. I was searching this converting, but I didn't find. So, I wrote it. I hope, it will be useful for somebody:

可能是,您需要逆转换,从std::stringString^。我正在搜索这个转换,但我没有找到。所以,我写了。我希望,这对某人有用:

String^ stdStringToPlatformString(string stdString){
    const size_t newsizew = strlen(stdString.c_str()) + 1;
    size_t convertedChars = 0;
    wchar_t *ch1 = new wchar_t[newsizew];
    mbstowcs_s(&convertedChars, ch1, newsizew, stdString.c_str(), _TRUNCATE);
    String ^platformString;
    platformString = ref new Platform::String(ch1, newsizew);
    return platformString;
}    

回答by Ion Vlad-Doru

string platformStringToStdString(String ^input){
    int size=input->Length()+1;
    char* auxiliary=(char *)malloc(sizeof(char)*size);
    wcstombs_s(NULL,auxiliary,size,input->Data(),_TRUNCATE);
    string result(auxiliary);
    free(auxiliary);
    return result;
}

回答by Aaron Fischer

I think you can also just do:

我认为你也可以这样做:

string dummy = string( textBox1->Text );

Check out How to: Convert Between Various String Typeson MSDN.

在 MSDN 上查看如何:在各种字符串类型之间转换