MATLAB: MxCreateString usage when calling matlab

mex

I try to call a function from mex in matlab and for this reason I made a mxArray because the function has two inputs namely a first one which is text and the second one which is a number.
My function works when I have static text, but not when I want to use the input to the mex-function. In the latter case I only get the first letter and not all 49 characters so I assume there is a problem with the pointers but I seriously cannot figure out were the problem lies
working code:
mxArray *callInput[2];
double inputNumber;
....
callInput[0] = mxCreateString("StringBeingPassed");
callInput[1] = mxCreateDoubleScalar(inputNumber);
mexCallMATLAB(0,NULL,2, callInput,"functionName");
NOT working anymore (only first letter being passed to function):
mxArray *callInput[2], *stringMX;
char *string_pr;
char string[49];
double inputNumber;
....
stringMX = mxGetField(prhs[0],0,"string");
string_pr = mxGetData(stringMX);
for (ii=0;ii<49;ii++){
*(yearString+ii) = *(yearString_pr+ii);
}
callInput[0] = mxCreateString(string);
callInput[1] = mxCreateDoubleScalar(inputNumber);
mexCallMATLAB(0,NULL,2, callInput,"functionName");

Best Answer

MATLAB strings are stored internally as 2 bytes per character, not 1 byte per character. For regular ASCII text, that means that one of those bytes will be 0 (i.e., a null character). So in your for-loop you are actually only copying half the string, and every other byte you are copying is a null character. So the mxCreateString function only sees the first character (the 2nd being the first null character). Hence only 1 character gets copied in the mxArray you are creating. Some options:
1) Skip all the character-by-character copying and just use what you want, since it is already in mxArray form (recommended):
callInput[0] = stringMX;
2) Use an official API function to do this. E.g. (maybe you need the text as a C-string for some reason),
character *string;
string = mxArrayToString(stringMX);
callInput[0] = mxCreateString(string);
mxFree(string);
You can do the character-by-character copying manually, but you would have to copy every-other-character of the input and then tack on the null character yourself, ensuring that you don't run over the end of the input string during the copy (i.e., don't hard code a 49).
Related Question