Converting Parameter from mxArray to a C-Style String

6 views (last 30 days)
I have a mexfunction where I input a total of 3 parameters: two double floating point values and one with a string of characters. My question is how do I take the string parameter and convert it to a C or C++ string so I can use it in the C++ file?
  2 Comments
James Tursa
James Tursa on 11 Mar 2020
Edited: James Tursa on 11 Mar 2020
Is the string parameter a char type using single quotes ' ' (in which case the answer will be easy), or is it a string class type using double quotes " " (in which case the answer is more work)?
Jerome Richards
Jerome Richards on 11 Mar 2020
I am passing it in double quotes. In MATLAB, I have:
mex my_mexfile.cpp
my_mexfile(x, y, "My String");
and in my C++ Mexfile, I have:
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const mxArray *pm = prhs[2];
char* str = (char*)malloc(15);
mwSize len = 15;
int v = mxGetString(pm, str, len);
printf("%s\n", str);
}
prhs[2] is what contains the string of characters. Whey I try reading and printing it, it displays completely random characters. What am I doing wrong?

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 11 Mar 2020
Edited: James Tursa on 11 Mar 2020
If it is a single quote ' ' char array, then just
char *cp;
cp = mxArrayToString(prhs[2]);
If it is a double quote " " string class variable, then a bit more work:
mxArray *mx;
char *cp;
if( mexCallMATLAB(1, &mx, 1, (mxArray **)(prhs+2), "char") ) {
mexErrMsgTxt("Unable to convert input string to char");
}
cp = mxArrayToString(mx);
mxDestroyArray(mx);
The way to tell if an input is one or the other is:
if( mxIsChar(prhs[2]) ) {
/* do the char stuff */
} else if( mxIsClass( prhs[2], "string" ) ) {
/* do the string stuff */
} else {
mexErrMsgTxt("Third input needs to be char or string");
}
cp will point to a C-style string. When you are done using it, it is good programming practice to free it:
mxFree(cp);

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) 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!