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.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v5.2.0/Character-Strings-in-Mex_002dFiles.html