C++ から MATLAB への列挙の引き渡し
この例では、列挙メンバーを matlab::data::EnumArray と定義し、MATLAB® 列挙メンバーを入力として必要とする MATLAB 関数を呼び出す方法を説明します。列挙配列を作成するには、matlab::data::ArrayFactory を使用します。matlab::data::EnumArray には、MATLAB クラス名と 1 つ以上の列挙メンバーが含まれています。MATLABEngine::setVariable を使用して、配列を変数として MATLAB ワークスペースに渡すこともできます。
メモ
matlab::data::EnumArray を MATLAB に渡すには、MATLAB パス上に名前付き MATLAB クラスが存在していなければなりません。
次の TextString を MATLAB で定義すると仮定します。このクラスは、TextColor という名前の特定の列挙型クラスであるプロパティを定義します。TextString クラス コンストラクターは、次の 2 つの入力引数を取ります。
Str— 1 行 n 列の char 配列Color—TextColorクラスの列挙メンバー
classdef TextString properties Str(1,:) char Color TextColor end methods function obj = TextString(str,color) if nargin == 2 obj.Str = str; obj.Color = color; end end end end
以下に、MATLAB の TextColor 列挙型クラスの定義方法を示します。
classdef TextColor enumeration Red Green Blue end end
この MATLAB ステートメントは、文字ベクトルと列挙メンバーをクラス コンストラクターに渡して TextString オブジェクトを作成します。
T = TextString('Any text string',TextColor.Blue);次のサンプル コードは、MATLAB の TextString オブジェクトを作成してプロパティ値を表示します。TextString オブジェクトを作成するには、次を行います。
MATLAB 文字ベクトル引数のための
matlab::data::CharArrayを定義する。MATLAB
TextColor.Blue列挙型引数のためのmatlab::data::EnumArrayを定義する。引数ベクトルを
MATLABEngine::fevalに渡す。MATLABEngine::getPropertyを使用してプロパティ値を取得して値を表示する。
メモ
この例では、ここで説明されている MATLAB の TextString クラスと TextColor クラスを定義する必要があります。これらのクラスは、この例で使用される共有 MATLAB セッションのパス上になければなりません。
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
void enumArray() {
using namespace matlab::engine;
// Connect to named shared MATLAB session started as:
// matlab -r "matlab.engine.shareEngine('myMatlabEngine')"
String session(u"myMatlabEngine");
std::unique_ptr<MATLABEngine> matlabPtr = connectMATLAB(session);
// Create MATLAB data array factory
matlab::data::ArrayFactory factory;
// Create enumeration array
auto enumColor = factory.createEnumArray({ 1,1 }, "TextColor", { "Blue" });
// Create argument vector
std::vector<matlab::data::Array> args({
factory.createCharArray("Any text string"),
enumColor});
// Call MATLAB TextString to create object
matlab::data::Array T = matlabPtr->feval(u"TextString", args);
// Get the value of the Str property
matlab::data::CharArray c = matlabPtr->getProperty(T, u"Str");
std::cout << "Str property value: " << c.toAscii() << std::endl;
// Get the value of the Color property from EnumArray col
matlab::data::EnumArray col = matlabPtr->getProperty(T, u"Color");
std::cout << "Color property class: " << col.getClassName() << std::endl;
std::cout << "Color property value: " << std::string(col[0]) << std::endl;
}
以下にプログラム出力を示します。
Str property value: Any text string Color property class: TextColor Color property value: Blue
C++ エンジン プログラムを設定およびビルドする方法の詳細については、Requirements to Build C++ Engine Applicationsを参照してください。
参考
matlab::data::EnumArray | matlab::data::ArrayFactory | matlab::engine::connectMATLAB | matlab::engine::MATLABEngine