Using C++ Mex Function how to get std::string argument?

42 views (last 30 days)
This seems like it should be simple, but I can't get either it to compile or not fail during runtime. Basically I need to have the Mex Function have 2 parameters which are both strings, and will be passed through to C++ functions inside. Can someome tell me how to go from matlab::mex::ArgumentList input, to 2 std::strings? I guess also what would function call look like from Matlab side?
Thanks,

Accepted Answer

Karola Gurrath
Karola Gurrath on 30 Jan 2019
I got the same problem yesterday and this is the solution I found. Maybe this is not the best way to get a std::string but it works and I could not find anything else...
Matlab-Code:
cellArray{1} = "string1";
cellArray{2} = "string2";
myMexFunction(cellArray);
myMexFunction:
using namespace matlab::data;
using matlab::mex::ArgumentList;
class MexFunction : public matlab::mex::Function
{
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
ArrayFactory factory;
public:
void operator()(ArgumentList outputs, ArgumentList inputs)
{
CellArray imageCell = std::move(inputs[0]);
TypedArrayRef<MATLABString> inArrayRef1 = imageCell[0];
std::string string1 = std::string(inArrayRef1[0]);
TypedArrayRef<MATLABString> inArrayRef2 = imageCell[1];
std::string string2 = std::string(inArrayRef2[0]);
// do something with string1 und string2...
}
}

More Answers (1)

cui,xingxing
cui,xingxing on 10 Aug 2022
Edited: cui,xingxing on 10 Aug 2022
matlab code
input1 = "string1";
input2 = "string2";
myMexFunction(input1,input2);
mex c++ code
using namespace matlab::data;
using matlab::mex::ArgumentList;
class MexFunction : public matlab::mex::Function
{
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
ArrayFactory factory;
public:
void operator()(ArgumentList outputs, ArgumentList inputs)
{
std::string string1 = std::string(inputs[0][0]);
std::string string2 = std::string(inputs[1][0]);
// or use following code
//std::string string1 =
// matlab::engine::convertUTF16StringToUTF8String(inputs[0][0]);
//std::string string2 =
// matlab::engine::convertUTF16StringToUTF8String(inputs[1][0]);
// do something with string1 und string2...
}
}
input1/2 argument is one string scalar in matlab, but it also represent 1 by 1 string matrix, so
directly specify sub-index [0][0] in c++.
BTW, to prevent matlab crash from incorrect input, It is best to have a check-uphad
if (inputs[0].getType() != matlab::data::ArrayType::MATLAB_STRING) {
matlabPtr->feval(u"error",
0, std::vector<matlab::data::Array>({factory.createScalar("The first input must string scalar")}));
}

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!