Converting Parameter from mxArray to a C-Style String
6 views (last 30 days)
Show older comments
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
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)?
Answers (1)
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);
0 Comments
See Also
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!