この文書の現在のバージョンと選択したバージョンの差分を表示します。
次のリビジョン | 前のリビジョン | ||
文字列 [2009/01/31 15:30] 192.168.0.63 作成 |
— (現在) | ||
---|---|---|---|
ライン 1: | ライン 1: | ||
- | ====== 文字列 ====== | ||
- | |||
- | C++/CLIの文字列操作は、System::Stringを使います。 | ||
- | |||
- | ソースコード中のリテラル文字列は、必要に応じてString^に格上げされます。 | ||
- | |||
- | 内部的にはwchar_t(UTF-16)で値を保持しています。 | ||
- | |||
- | char*やwchar_t*からStringへの変換は | ||
- | <code cpp> | ||
- | const char* p = "AAA"; | ||
- | String^ s = gcnew String(p); | ||
- | </code> | ||
- | でできます。 | ||
- | |||
- | 逆の変換は | ||
- | |||
- | 1、const wchar_t*がほしい場合は | ||
- | <code cpp> | ||
- | #include <vcclr.h> | ||
- | |||
- | String^ s = L"AAA"; | ||
- | pin_ptr<const wchar_t> pIn = PtrToStringChars(s); | ||
- | </code> | ||
- | 2、コピーがほしい場合は | ||
- | |||
- | StringToHGlobalAnsiまたはStringToHGlobalUniを使います。 | ||
- | <code cpp> | ||
- | std::string getStdString(String^ s) | ||
- | { | ||
- | std::string ret; | ||
- | System::IntPtr pp = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(s); | ||
- | ret = (const char*)pp.ToPointer() ; | ||
- | System::Runtime::InteropServices::Marshal::FreeHGlobal(pp); | ||
- | return ret; | ||
- | } | ||
- | |||
- | std::wstring getStdWstring(String^ s) | ||
- | { | ||
- | std::wstring ret; | ||
- | System::IntPtr pp = System::Runtime::InteropServices::Marshal::StringToHGlobalUni(s); | ||
- | ret = (const wchar_t*)pp.ToPointer() ; | ||
- | System::Runtime::InteropServices::Marshal::FreeHGlobal(pp); | ||
- | return ret; | ||
- | |||
- | } | ||
- | </code> | ||
- | Ansiに変換すると情報が劣化する場合があるので注意が必要です。 | ||
- | |||
- | Stringの基本事項として、一度設定したら内部の文字列は変化しない(内部の文字列を変更するメソッドはない)があります。 | ||
- | |||
- | また、Stringに対してで暗黙のCLRサポートがあります。 | ||
- | |||
- | |||
- | - ==で比較すると、ハンドルの比較ではなくて文字列の比較が行われる。!=も同様 | ||
- | - +で色々な型を足すことができる。 | ||
- | |||
- | これら関してはC++との互換性で影響が出ることがあります。 | ||
- | |||
- | 以下のC++コードはC++/CLIだとコンパイルエラーになります。 | ||
- | <code cpp> | ||
- | #include "stdio.h" | ||
- | int main(int argc, char* argv[]) | ||
- | { | ||
- | const char* p = "ABC" + 1; | ||
- | printf(p); | ||
- | return 0; | ||
- | } | ||
- | </code> | ||
- | 空文字の扱い | ||
- | |||
- | 空文字を扱うための仕組みもあるので""やL""よりもこちらを使うほうがいいかもしれません。 | ||
- | <code cpp> | ||
- | if ( s == nullptr || s->Length == 0 ) | ||
- | return; | ||
- | </code> | ||
- | の代わりに | ||
- | <code cpp> | ||
- | if ( String::IsNullOrEmpty(s) ) | ||
- | return; | ||
- | </code> | ||
- | |||
- | |||
- | 同様に | ||
- | <code cpp> | ||
- | return L""; | ||
- | </code> | ||
- | の代わりに | ||
- | <code cpp> | ||
- | return String::Empty; | ||
- | </code> |