MATLAB: How to pass a string from a C++ Mex file to the MATLAB workspace

cc/c++c++ implementationconversiondata typeMATLABmexmex filemx

I am trying to pass a string from a C++ Mex file I am working on to the MATLAB workspace for plotting purposes. It is a fairly complicated program, but all I want to do is pass a std::string in my MexFunction (which I defined as "var") to the MATLAB workspace. This is the important part of the code:
#include "mex.hpp"
#include "mexAdapter.hpp"
using namespace matlab::data;
using namespace matlab::engine;
using namespace std;
using matlab::mex::ArgumentList;
// "some code here" //
class MexFunction : public matlab::mex::Function{
public:
void operator()(ArgumentList outputs, ArgumentList inputs){
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
ArrayFactory factory;
// "more code here" //
for(int i = 0; i < 100; i++){
std::vector<ToolData> toolData = apiSupportsBX2 ? capi.getTrackingDataBX2() : capi.getTrackingDataBX();
for (int i = 0; i < toolData.size(); i++)
{
std::string var = toolDataToCSV(toolData[i]);
std::cout << var << std::endl;
// Pass "var" to MATLAB here //
}
usleep(5000);
}
matlabPtr->eval(u"printData = true");
// "more code here" //
std::cout << "Press Enter to continue...";
std::cin.ignore();
}
};
I'm fairly new to C++/MATLAB-implementations and don't have that much experience with Mex file programming, so thanks in advance!

Best Answer

matlab:engine::setvariable seems to be the function to do that. With your original C++ code (not the C interface)
matlabPtr->setVariable(u"variablename", var); //%don't use var as variable name in matlab. It's the variance function.
Untested. I've never used the C++ interface.
Related Question