Convert Matlab struct into custom C++ type with C++ Mex API

16 ビュー (過去 30 日間)
Friedrich
Friedrich 2024 年 10 月 25 日
編集済み: 埃博拉酱 2024 年 10 月 28 日
I am trying to mex a custom C++ code file but am struggeling in how to convert the Matlab-Inputs into whatever type I need for my C++ Code.
Let's assume I have a Matlab struct like this
u = struct(test1 = 5, test2 = 10, test3 = struct(test4 = 1:10))
u = struct with fields:
test1: 5 test2: 10 test3: [1x1 struct]
As u see I have a nested struct with an array inside. Now, in the C++ Mex API I need to read all values of the above struct. How do I do this? I tried indexing into the inputs of the operator() method
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs)
however, that way I could only retrieve the number of inputs but not their numerical contents.
I guess I have to do something like
matlab::data::TypedArray<Struct> in0 = std::move(inputs[0]);
to get to the values but that alone doesn't help me. How do I proceed?

採用された回答

埃博拉酱
埃博拉酱 2024 年 10 月 25 日
編集済み: 埃博拉酱 2024 年 10 月 28 日
Usually you should move-construct a StructArray from inputs[0] and index into it to get a Struct element, which can be then indexed with a fieldname as a C++ string to get a generic Array, with which you can then move-construct a TypedArray of correct type (get its real runtime type with Array::GetType if you can't ensure it at coding time). Finally you should usually index into that TypedArray to get a numeric element, get an iterator like cbegin/begin, or release it as a buffer_ptr_t to get a C++ native pointer.
void Example(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs)
{
matlab::data::TypedArray<double> A = matlab::data::StructArray(matlab::data::StructArray(std::move(inputs[0]))[0]["test3"].operator matlab::data::Array())[0]["test4"];
A.cbegin();//Get an iterator
A[0];//Get a double element
const matlab::data::buffer_ptr_t<double> B = A.release();//After this, A becomes invalid
B.get();//Get a native pointer
}
20241028:Edited for forgetting to provide a type to the buffer_ptr_t
  2 件のコメント
Friedrich
Friedrich 2024 年 10 月 28 日
Thanks @埃博拉酱, that helped!
Is it also possible to move the content of the Array A to a std::vector<double> v?
Just for the sake of completeness, I guess you forgot to provide a type to the buffer_ptr_t. This compiles:
const matlab::data::buffer_ptr_t<double> B = A.release();
埃博拉酱
埃博拉酱 2024 年 10 月 28 日
編集済み: 埃博拉酱 2024 年 10 月 28 日
No. std::vector does not support moving constructs from types other than vector. Copying is inevitable if you really must get a vector.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCall C++ from MATLAB についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by