MATLAB: How to use the mxCreateCharArray routine in the C-Mex function

cMATLABmexmxcreatechararrayroutine

I would like to put a two dimensional array of characters into the MATLAB environment from my C Mex-file. I would like to use the mxCreateCharArray routine to do that.

Best Answer

The mxCreateCharArray routine is similar to the mxCreateNumericArray routine in the sense that they both create multidimensional arrays. The first is an array of characters and the second is different data types.
The lines of code below demonstrate an example with mxCreateCharArray:
/*Filename: TEST.C*/
#include <string.h>
#include "mex.h"
#define TOTAL_ELEMENTS 4
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
int bytes_to_copy;
mxChar *dataptr;
mxChar data[]={'a','b','c','d'};
int dims[] = {2, 2};
/* Check for proper number of input and output arguments */
if (nrhs > 1) {
mexErrMsgTxt("Too many input arguments.");
}
if(nlhs > 1){
mexErrMsgTxt("Too many output arguments.");
}
/* Create a 2-Dimensional string mxArray. */
plhs[0]= mxCreateCharArray(2, (const int *)dims);
/* populate the real part of the created array */
dataptr = (mxChar *)mxGetData(plhs[0]);
bytes_to_copy = TOTAL_ELEMENTS * mxGetElementSize(plhs[0]);
memcpy(dataptr,data,bytes_to_copy);
}
At the MATLAB Command prompt you will get:
>> mex test.c
>> test
ans =
ac
bd