Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
Rakesh Sadhu
Rakesh Sadhu am 15 Okt. 2021
Beantwortet: Harsh Mahalwar am 7 Mär. 2024
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 .

Antworten (1)

Harsh Mahalwar
Harsh Mahalwar am 7 Mär. 2024
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!

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by