Converting Parameter from mxArray to a C-Style String
Afficher commentaires plus anciens
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 commentaires
James Tursa
le 11 Mar 2020
Modifié(e) : James Tursa
le 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
le 11 Mar 2020
Réponses (1)
James Tursa
le 11 Mar 2020
Modifié(e) : James Tursa
le 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);
Catégories
En savoir plus sur Write C Functions Callable from MATLAB (MEX Files) dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!