User`s manual

Examples of C MEX-Files
2-13
status = mxGetString(prhs[0], input_buf, buflen);
if(status != 0)
mexWarnMsgTxt("Not enough space. String is truncated.");
/* Call the C subroutine. */
revord(input_buf, buflen, output_buf);
/* Set C-style string output_buf to MATLAB mexFunction output*/
plhs[0] = mxCreateString(output_buf);
return;
}
The gateway routine allocates memory for the input and output strings. Since
these are C strings, they need to be one greater than the number of elements
in the MATLAB string. Next the MATLAB string is copied to the input string.
Both the input and output strings are passed to the computational subroutine
(
revord), which loads the output in reverse order. Note that the output buffer
is a valid null-terminated C string because
mxCalloc initializes the memory to
0. The API function
mxCreateString then creates a MATLAB string from the
C string,
output_buf. Finally, plhs[0], the left-hand side return argument to
MATLAB, is set to the MATLAB array you just created.
By isolating variables of type
mxArray from the computational subroutine, you
can avoid having to make significant changes to your original C code.
In this example, typing
x = 'hello world';
y = revord(x)
produces
The string to convert is 'hello world'.
y =
dlrow olleh
Passing Two or More Inputs or Outputs
The plhs[] and prhs[] parameters are vectors that contain pointers to each
left-hand side (output) variable and each right-hand side (input) variable,
respectively. Accordingly,
plhs[0] contains a pointer to the first left-hand side
argument,
plhs[1] contains a pointer to the second left-hand side argument,