Converting Parameter from mxArray to a C-Style String
显示 更早的评论
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 个评论
James Tursa
2020-3-11
编辑:James Tursa
2020-3-11
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
2020-3-11
回答(1 个)
James Tursa
2020-3-11
编辑:James Tursa
2020-3-11
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);
类别
在 帮助中心 和 File Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!