2

String^ を基本的な文字列に変換しようとしましたが、このコードの後に​​エラーが発生します。それはどういう意味ですか、どうすれば修正できますか? 基本的な文字列をクラス コンストラクターに入力する必要があります。文字列 ^ は機能しません。

System::String^ temp = textBox1->Text;
string dummy = System::Convert::ToString(temp);
エラー C2440: '初期化中': 'System::String ^' から 'std::basic_string' に変換できません
1>と
1>[
1> _Elem=文字、
1> _Traits=std::char_traits,
1> _Ax=std::アロケータ
1> ]
1> ソース型を取得できるコンストラクターがないか、コンストラクターのオーバーロードの解決があいまいです
4

6 に答える 6

9

ストリングをマーシャリングする必要があります。管理対象の文字列は、管理対象のヒープのどこかにあります(ガベージコレクターは自由に移動できます)。

文字列をネイティブ側に取得する1つの方法は、次のとおりです。

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

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));
于 2009-04-22T05:06:39.387 に答える
3

私は解決策を見つけるために11時間を費やします:

 #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;
于 2010-12-12T13:37:01.880 に答える
2

System::Stringaを aに変換するには、次の 2 つのことを行う必要がありますstd::string

  • マネージド ヒープのメモリをアンマネージド ヒープにマーシャリングします。
  • 文字エンコーディングをワイド文字から (質問のように見える) ansi 文字に変換します。

1 つの方法は、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..
}

そして、次のように使用します。

// 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
}

これにより、選択したエンコーディング (ascii よりも utf-8 など) を使用することもできますが、これは実際には必要ない場合があります。

于 2009-04-22T06:08:45.710 に答える
0
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;
}
于 2013-03-12T16:38:58.073 に答える
0

あなたもできると思います:

string dummy = string( textBox1->Text );

MSDNの「方法:さまざまな文字列型の間で変換する」を参照してください。

于 2009-04-22T05:36:12.420 に答える