Search code examples
matlabs-function

Why char is stored as 2 bytes in Matlab S-Function


I would like to pass an uint8 array to my S-Function as a parameter:

inParam = char(uint8(1:7))

In the S-Function I did the followings

UINT8_T *inParam = (UINT8_T *)mxGetPr(ssGetSFcnParam(S, PARAM_IN_PORT_NR)); //;

but I saw that actually the array elements are stored as 2 bytes.

UINT16_T *inPorts = (UINT16_T *)mxGetPr(ssGetSFcnParam(S, PARAM_IN_PORT_NR)); //
// I can loop through the data
// This is only a snippet
*(inPorts++);

Why is that? Is this happening in all the Matlab versions?


Solution

  • MATLAB uses UTF-16 encoding for character vectors and strings. For example, see the definition of matlab::engine::String as a std::basic_string<char16_t>. This is the same on all platforms. I don't know when exactly Unicode support was introduced in MATLAB, but you can assume that any version from the last 15 years uses 16-bit character encoding.

    Consider using mxGetString to get an 8-bit (ASCII) representation of the string, or mxArrayToString if you need to support Unicode characters.