MATLAB コマンド ウィンドウの出力を C++ にリダイレクト
MATLAB® は、エラー メッセージおよびステートメントからの出力を MATLAB コマンド ウィンドウに表示します。これらの例では、文字列バッファーを使用してこの出力を取得し、feval、fevalAsync、eval、またはevalAsyncメンバー関数で返して、この出力を C++ プログラムにリダイレクトする方法を示します。
C++ エンジン プログラムを設定およびビルドする方法の詳細については、Requirements to Build C++ Engine Applicationsを参照してください。
画面出力のリダイレクト
この例では、MATLAB の 2 つのステートメントを評価します。これらのステートメントは、MATLAB ワークスペースに 3 つの変数を作成します。このコードが MATLAB 関数 whos
を呼び出し、これによって MATLAB コマンド ウィンドウに現在のワークスペース変数が表示されます。MATLABEngine::eval
への呼び出しでバッファーへのポインターを渡すことにより、文字列バッファーの MATLAB 標準出力を取得します。
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void screenOutput() {
using namespace matlab::engine;
// Start MATLAB engine synchronously
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
// Evaluate statements that create variables
matlabPtr->eval(u"[X,Y] = meshgrid(-2:.2:2);");
matlabPtr->eval(u"Z = X.*exp(-X.^2 - Y.^2);");
// Create string buffer for standard output
typedef std::basic_stringbuf<char16_t> StringBuf;
std::shared_ptr<StringBuf> output = std::make_shared<StringBuf>();
// Display variables in the MATLAB workspace
matlabPtr->eval(u"whos", output);
// Display MATLAB output in C++
String output_ = output.get()->str();
std::cout << convertUTF16StringToUTF8String(output_) << std::endl;
}
エラー出力のリダイレクト
この例では、すべての変数を MATLAB ワークスペースから削除した後で変数を参照することにより、MATLAB エラーを発生させます。メンバー関数 MATLABEngine::eval
に渡された文字列バッファーが try/catch コード ブロック内にあるエラー メッセージを取得します。
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void errorOutput() {
using namespace matlab::engine;
// Start MATLAB engine synchronously
std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
// Create string buffer for standard output
typedef std::basic_stringbuf<char16_t> StringBuf;
std::shared_ptr<StringBuf> error = std::make_shared<StringBuf>();
// Evaluate statement that causes error
matlabPtr->eval(u"clear");
try {
matlabPtr->eval(u"x + 2;", {}, error);
}
catch (...) {
String error_ = error.get()->str();
std::cout << convertUTF16StringToUTF8String(error_) << std::endl;
}
}
参考
matlab::engine::MATLABEngine
| matlab::engine::startMATLAB
| matlab::engine::convertUTF16StringToUTF8String