「C++の応用 - C Sharp DLLの使用」の版間の差分

ナビゲーションに移動 検索に移動
532行目: 532行目:
     // メモリの解放
     // メモリの解放
     mono_free(stringValue);
     mono_free(stringValue);
}
</syntaxhighlight>
<br>
===== 戻り値が配列の場合 (非コレクション) =====
以下の例では、C#ライブラリのメソッドの戻り値はint型の配列であり、C++でそれを受け取っている。<br>
<br>
まず、<code>mono_runtime_invoke</code>関数でC#のメソッドを呼び出して、戻り値を<code>MonoObject*</code>型で受け取る。<br>
次に、<code>reinterpret_cast</code>を使用して<code>MonoObject*</code>型を<code>MonoArray*</code>に変換する。<br>
最後に、<code>mono_array_get</code>関数を使用して<code>int</code>型の配列の各要素を取得している。<br>
<br>
<syntaxhighlight lang="c#">
// C#ライブラリ
public int[] RetList()
{
    return [1, 2, 3];
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="c++">
// C++
MonoObject *pResult = mono_runtime_invoke(method, instance, nullptr, &exc);
// エラーの確認
if (exc != nullptr) {
    // エラー情報の取得
    // ...略
}
else {
    // MonoObject*型をint型の配列に変換
    MonoArray* resultArray = reinterpret_cast<MonoArray*>(pResult);
    // 配列の長さを取得
    auto arrayLength = mono_array_length(resultArray);
    // int型の配列に変換
    std::vector<int> ivec(0, 0);
    for (auto i = 0; i < arrayLength; i++) {
      // MonoArray*型をint型に変換
      ivec.push_back(mono_array_get(resultArray, int, i));
    }
    for (auto i : ivec) {
      std::cout << i << std::endl;
    }
  }
  }
  </syntaxhighlight>
  </syntaxhighlight>

案内メニュー