外部インタフェース/API | ![]() ![]() |
MATLABからFortran MEX-ファイルに文字列を渡すことは簡単です。つぎのプログラムは、文字列を受け取りキャラクタを反対の順番にして出力します。
C $ Revision: 1.14 $ C============================================================== 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============================================================== 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
C The gateway routine subroutine mexFunction(nlhs, plhs, nrhs, prhs) integer nlhs, nrhs C-------------------------------------------------------------- C (pointer) Replace integer by integer*8 on the DEC Alpha C platform. C integer plhs(*), prhs(*) integer mxCreateString, mxGetString C-------------------------------------------------------------- C integer mxGetM, mxGetN, mxIsString 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(mxIsString(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
正しい入力数をチェックした後に、このMEX-ファイルゲートウェイルーチンは入力が行または列ベクトルの文字列であることを確認します。それから文字列のサイズを調べ、文字列をFortranキャラクタ配列に設定します。キャラクタ文字列の場合、mxCopyPtrToCharacter
を使ってFortranキャラクタ配列にデータをコピーする必要はありません。実際に、mxCopyPtrToCharacter
は、MAT-ファイルにのみ動作します。MAT-ファイルについての詳細は、「データの読み込みと書き出し」を参照してください。
x = 'hello world';
y = revord(x)
y = dlrow olleh
![]() | 第一の例 -- スカラを渡す | 文字列配列を渡す | ![]() |