How do I convert a UTF-8 C-string to an mxArray of mxChar in C code?
4 views (last 30 days)
Show older comments
MathWorks Support Team
on 15 Mar 2017
Answered: MathWorks Support Team
on 5 Apr 2017
How do I convert a UTF-8 C-string to an mxArray of mxChar in C code?
Accepted Answer
MathWorks Support Team
on 15 Mar 2017
This is a two step process. The first phase is performed in C and the second phase in MATLAB (called from C).
(1) In the C code, you will need to create an mxArray of UINT8 from the UTF-8 C-string. If you intend to have multiple rows of characters in your array, keep in mind that MATLAB stores arrays in column-major order.
(2) In MATLAB you will need to use the 'native2unicode' function to convert the array of 'uint8' to an array of 'char'.
For example, if this conversion is taking place in a MEX file, the code would look something like this: (NOTE: This code does not compile as-is)
//UTF-8 string to convert
char utf8str[] = {65 66 67 68 207 163};
// Step 1 - create a mwArray of uint8 from UTF-8 encoded C-string
// **YOUR FUNCTION** Convert C-string to mwArray of uint8
mwArray* uint8Array = UTF8CStringToMwArrayUint8(utf8str, length);
//Step 2 - convert mwArray of uint8 to mwArray of char using 'native2unicode'
mwArray* encodingString = mxCreateString("UTF-8");
mwArray* lhs_native2unicode[1];
mwArray* rhs_native2unicode[] = {uint8Array, encodingString};
// Calling 'native2unicode'
mexCallMATLAB(1, &lhs_native2unicode, 2, &rhs_native2unicode, 'native2unicode');
// this is the converted char array
mwArray* charArray = lhs_native2unicode[1];
0 Comments
More Answers (0)
See Also
Categories
Find more on Deploy to C++ Applications Using mwArray API (C++03) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!