Main Content

Pass Strings in C MEX File

This example shows how to pass strings to a MEX function built with the C Matrix API. The example revord.c accepts a character vector and returns the characters in reverse order.

C Code Analysis

To see the code, open revord.c in the MATLAB® Editor.

The gateway function, mexFunction, creates a C string from the input variable, prhs[0]. By isolating variables of type mxArray from the computational subroutine, revord, you can avoid making significant changes to your original C and C++ code.

Convert the input argument prhs[0] to a C-style string input_buf.

input_buf = mxArrayToString(prhs[0]);

Allocate memory for the output argument, output_buf, a C-style string.

output_buf = mxCalloc(buflen, sizeof(char));

The size of the output argument is equivalent to the size of the input argument.

Call the computational subroutine, revord.

revord(input_buf, buflen, output_buf);

Convert the output, output_buf, to an mxArray and assign to plhs[0].

plhs[0] = mxCreateString(output_buf);

Do not release memory for this variable because it is an output argument.

The mxArrayToString function, used to create the temporary input_buf variable, allocates memory; use the mxFree function to release the memory.

mxFree(input_buf);

Build and Test Example

Run the following commands from the MATLAB command line.

Build the example.

mex -v revord.c

Call the function.

x = 'hello world';
y = revord(x)
y =
dlrow olleh

Related Topics