Borrar filtros
Borrar filtros

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

4 visualizaciones (últimos 30 días)
Rakesh Sadhu
Rakesh Sadhu el 15 de Oct. de 2021
Respondida: Harsh Mahalwar el 7 de Mzo. de 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 .

Respuestas (1)

Harsh Mahalwar
Harsh Mahalwar el 7 de Mzo. de 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!

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by