External Interfaces/API |
Passing strings from MATLAB to a Fortran MEX-file is straightforward. This program accepts a string and returns the characters in reverse order.
C============================================================== C revord.f C Example for illustrating how to copy string data from C MATLAB to a Fortran-style string and back again. C C Takes a string and returns a string in reverse order. C C This is a MEX-file for MATLAB. C Copyright (c) 1984-2000 The MathWorks, Inc. C $Revision: 1.9 $ C============================================================== C Computational subroutine subroutine revord(input_buf, strlen, output_buf) character input_buf(*), output_buf(*) integer i, strlen do 10 i=1,strlen output_buf(i) = input_buf(strlen-i+1) 10 continue return end
Below is the gateway routine that calls the computational routine.
C The gateway routine subroutine mexFunction(nlhs, plhs, nrhs, prhs) C-------------------------------------------------------------- C (pointer) Replace integer by integer*8 on the DEC Alpha C platform. integer plhs(*), prhs(*) integer mxCreateString, mxGetString C-------------------------------------------------------------- integer nlhs, nrhs integer mxGetM, mxGetN, mxIsChar integer status, strlen character*100 input_buf, output_buf C Check for proper number of arguments. if (nrhs .ne. 1) then call mexErrMsgTxt('One input required.') elseif (nlhs .gt. 1) then call mexErrMsgTxt('Too many output arguments.') C The input must be a string. elseif(mxIsChar(prhs(1)) .ne. 1) then call mexErrMsgTxt('Input must be a string.') C The input must be a row vector. elseif (mxGetM(prhs(1)) .ne. 1) then call mexErrMsgTxt('Input must be a row vector.') endif C Get the length of the input string. strlen = mxGetM(prhs(1))*mxGetN(prhs(1)) C Get the string contents (dereference the input integer). status = mxGetString(prhs(1), input_buf, 100) C Check if mxGetString is successful. if (status .ne. 0) then call mexErrMsgTxt('String length must be less than 100.') endif C Initialize outbuf_buf to blanks. This is necessary on some C compilers. output_buf = ' ' C Call the computational subroutine. call revord(input_buf, strlen, output_buf) C Set output_buf to MATLAB mexFunction output. plhs(1) = mxCreateString(output_buf) return end
After checking for the correct number of inputs, this MEX-file gateway routine verifies that the input was either a row or column vector string. It then finds the size of the string and places the string into a Fortran character array. Note that in the case of character strings, it is not necessary to copy the data into a Fortran character array by using mxCopyPtrToCharacter
. In fact, mxCopyPtrToCharacter
works only with MAT-files. For more information about MAT-files, see Importing and Exporting Data.
A First Example -- Passing a Scalar | Passing Arrays of Strings |