【C++/CLI】System::String^をdouble/intに変換する

まず前提は以下の通り。

// これは .NETの型
System::String^ str = "10;"

// こっちは .NET/C++(CLI)共通で使える型
double d = 0;

変換に使うメソッドはいくつかあるのでそれぞれの使い方です。

System::String^ str = "10";
double d = 0;
int i = 0;

// ★★doubleに変換する(1)
try {
    // 変換に失敗すると例外でる
    d = double::Parse(str);
}
catch (System::Exception^ ex) { // ハンドルしないとアプリが落ちる
    // System::FormatException
    // >入力文字列の形式が正しくありません。
    std::cout
        << msclr::interop::marshal_as<std::string>(ex->Message).c_str()
        << std::endl;
}

// ★★doubleに変換する(2)
// bool System::Double::TryParse(System::String ^s, double% result);
// double::TryParse と書ける
if(double::TryParse(str, d)){
    std::cout << "処理成功=" << d << std::endl;
}

// ★★doubleに変換する(3)
// System::Convert::ToDouble(System::String ^s);
d = System::Convert::ToDouble(str);

// ------------------------------------

// ★★intに変換する(1)
try {
    // 変換に失敗すると例外でる
    i = int::Parse(str);
}
catch (System::Exception^ ex) { // ハンドルしないとアプリが落ちる
    // System::FormatException
    // >入力文字列の形式が正しくありません。
    std::cout
        << msclr::interop::marshal_as<std::string>(ex->Message).c_str()
        << std::endl;
}

// ★★intに変換する(2)
// bool System::Int32::TryParse(System::String ^s, int% result);
// int::TryParse と書ける
if(int::TryParse(str, i)){
    std::cout << "処理成功=" << i << std::endl;
}

// ★★intに変換する(3)
// bool System::Convert::ToInt32(System::String ^s);
i = System::Convert::ToInt32(i);

配列の場合、各要素はdouble型で .NET, C++/CLI共通となり TryParse の第2引数に渡せます。

System::String^ str = "10";

// ★★double**型はPure C++の型
double** values = new double* [10];
values[0] = new double[10];

if (double::TryParse(str, values[0][0])) { // 各要素はdoubleなのでout引数に渡せる
    std::cout << "result=" << values[0][0] << std::endl; // result=10
}

delete[] values[0];
delete[] values;

// ★★C++/CLIの配列の場合も各要素はdoubleなので渡せる
array<double>^ dArrayCli = gcnew array<double>(10);
if (double::TryParse(str, dArrayCli[0])) {
    std::cout << "result=" << dArrayCli[0] << std::endl;
}