How do I store a string from a MATLAB structure into a C structure in a MEX file?
Show older comments
I am building a MEX file that converts a MATLAB structure to a C structure, manipulates the C structure, and returns a modified MATLAB structure. A portion of the code that produces behavior I cannot explain is shown below. In the code portion, the variable "mx" is an mxArray structure, and the variable "cstructu" is a C structure.
field = mxGetField(mx, 0, "Field1");
ch = mxArrayToString(field);
strcpy(cstructu->Field1,ch);
mexPrintf("\n%s",cstructu->Field1);
field = mxGetField(mx, 0, "Field2");
ch = mxArrayToString(field);
strcpy(cstructu->Field2,ch);
mexPrintf("\n%s",cstructu->Field2);
field = mxGetField(mx, 0, "Field3");
ch = mxArrayToString(field);
strcpy(cstructu->Field3,ch);
mexPrintf("\n%s",cstructu->Field3);
mexPrintf("\n%s",cstructu->Field1);
mexPrintf("\n%s",cstructu->Field2);
mexPrintf("\n%s",cstructu->Field3);
The above code is divided into four code "blocks". The first three code blocks end in a "mexPrintf" statement that outputs to the command prompt the value stored for a given field in the C structure. The outputs from these three statements are as expected. The issue is with the "mexPrintf" statements in the fourth code block. When I print the value of "Field1", I get a concatenation of the values of "Field1", "Field2", and "Field3". When I print the value of "Field2", I get a concatenation of the values of "Field2" and "Field3". And when I print the value of "Field3", I just get the value of "Field3". What causes this behavior, and what do I need to do to correct it?
Accepted Answer
More Answers (0)
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!