How to send UTF std::string back to Matlab?
2 次查看(过去 30 天)
显示 更早的评论
class MexFunction : public matlab::mex::Function {
public:
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs)
{
ArrayFactory factory;
matlab::data::CharArray string1 = inputs[0];
plist_file = string1.toAscii();
std::string json_str = convertToJson(plist_file);// this function reads the file and returns the json string
matlab::data::CharArray str_json = factory.createCharArray(json_str);
outputs[0] = str_json;
}
};
This fails at Matlab execution , says only ascii characters allowed , which i understand why .
0 个评论
回答(1 个)
Harsh Mahalwar
2024-3-7
Hi Rakesh,
From what I can gather, you are trying to send std::string (UTF-8) from C++ to MATLAB and getting an exception saying, “Input data can only contain ASCII characters”.
Here’s a workaround to send std::string (UTF-8) from C++ to MATLAB:
#include "mex.h"
#include <string>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
// Sample UTF-8 string
std::string utf8String = u8"サンプル文字列"; // Translates to : "Sample String"
// Convert std::string to C-style string
const char *cStr = utf8String.c_str();
plhs[0] = mxCreateString(cStr);
}
(file name: sendingUTF8.cpp)
After saving sendingUTF8.cpp run the following command in the MATLAB terminal:
(output on successful compilation)
After successfully compiling sendingUTF8.cpp you can run the following command to display the UTF-8 string received from C++:
disp(sendingUTF8);
(string successfully displayed in MATLAB, translates to "Sample String")
I hope this helps, thanks!
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!