Character Strings in Mex-Files (GNU Octave (version 10.0.90))

#### A.2.3 Character Strings in Mex-Files ¶

As mex-files do not make the distinction between single and double quoted strings that Octave does, there is perhaps less complexity in the use of strings and character matrices. An example of their use that parallels the demo in `stringdemo.cc` is given in the file `mystring.c`, as shown below.

    #include <string.h>
    #include "mex.h"

    void
    mexFunction (int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
    {
      mwSize m, n;
      mwIndex i, j;
      mxChar *pi, *po;

      if (nrhs != 1 || ! mxIsChar (prhs[0])
          || mxGetNumberOfDimensions (prhs[0]) > 2)
        mexErrMsgTxt ("ARG1 must be a char matrix");

      m = mxGetM (prhs[0]);
      n = mxGetN (prhs[0]);
      pi = mxGetChars (prhs[0]);
      plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS, mxREAL);
      po = mxGetChars (plhs[0]);

      for (j = 0; j < n; j++)
        for (i = 0; i < m; i++)
          po[j*m + m - 1 - i] = pi[j*m + i];
    }

An example of its expected output is

    mystring (["First String"; "Second String"])
    ⇒ Second String
       First String

Other functions in the mex interface for handling character strings are `mxCreateString`, `mxArrayToString`, and `mxCreateCharMatrixFromStrings`. In a mex-file, a character string is considered to be a vector rather than a matrix. This is perhaps an arbitrary distinction as the data in the `mxArray` for the matrix is consecutive in any case.