External Interfaces Previous page   Next Page

Passing Strings

Any MATLAB data type can be passed to and from MEX-files. For example, this C code accepts a string and returns the characters in reverse order.

In this example, the API function mxCalloc replaces calloc, the standard C function for dynamic memory allocation. mxCalloc allocates dynamic memory using the MATLAB memory manager and initializes it to zero. You must use mxCalloc in any situation where C would require the use of calloc. The same is true for mxMalloc and mxRealloc; use mxMalloc in any situation where C would require the use of malloc and use mxRealloc where C would require realloc.

Below is the gateway routine that calls the C computational routine revord.

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

produces


Previous page  A First Example -- Passing a Scalar Passing Two or More Inputs or Outputs Next page

© 1994-2005 The MathWorks, Inc.