How to send UTF std::string back to Matlab?

조회 수: 10 (최근 30일)
Rakesh Sadhu
Rakesh Sadhu 2021년 10월 15일
답변: Harsh Mahalwar 2024년 3월 7일
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 .

답변 (1개)

Harsh Mahalwar
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!

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by