How to create matlab::data::CharArrayRef for matlab::data::CharArray?
3 views (last 30 days)
Show older comments
Florian Wolters
on 13 Dec 2021
Answered: Eswaramoorthy
on 28 Feb 2023
I'm using the C++ (not C!) MATLAB Data API from MATLAB R2019b. I would like to handle data referenced by a matlab::data::CharArray and a matlab::data::CharArrayRef in the same manner, i.e. I would like to implement something such as the following in C++ without using code duplication:
std::string toString(matlab::data::CharArray const& in) {
// TODO(2021-12-13 by wolters): How-to create `CharArrayRef` from
// `CharArray` in order to call the other toString function and avoid
// code duplication?
auto const multiByte = in.toUTF16();
return std::string{multiByte.begin(), multiByte.end()};
}
std::string toString(matlab::data::CharArrayRef const& in) {
auto const multiByte = in.toUTF16();
return std::string{multiByte.begin(), multiByte.end()};
}
I've tried a lot, but can't find a way to create an instance of matlab::data::CharArrayRef from an existing matlab::data::CharArray. (the same applies to other data types of the MATLAB Data API). Do you know how to achieve that?
0 Comments
Accepted Answer
Eswaramoorthy
on 28 Feb 2023
Hi
Yes, you can create an instance of matlab::data::CharArrayRef from an existing matlab::data::CharArray by using the createArrayRef function. Here's an example of how you could modify your code to avoid code duplication:
std::string toString(matlab::data::CharArray const& in) {
auto const multiByte = in.toUTF16();
return std::string{multiByte.begin(), multiByte.end()};
}
std::string toString(matlab::data::CharArrayRef const& in) {
auto const multiByte = in.toUTF16();
return std::string{multiByte.begin(), multiByte.end()};
}
// Wrapper function that calls the appropriate toString function
std::string toStringWrapper(const matlab::data::CharArray& in) {
return toString(in.createArrayRef());
}
In the toStringWrapper function, we create a matlab::data::CharArrayRef object from the matlab::data::CharArray input using the createArrayRef function. This matlab::data::CharArrayRef object can then be passed to the toString function that takes a matlab::data::CharArrayRef input. By using this wrapper function, you can avoid code duplication while still being able to handle both matlab::data::CharArray and matlab::data::CharArrayRef inputs in the same manner
0 Comments
More Answers (0)
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!