外部インタフェース/API | ![]() ![]() |
文字列を渡す
任意のMATLABデータタイプを、MEX-ファイルで受け渡すことができます。たとえば、つぎのCコードは、文字列を受け取り、反対の順番にしてキャラクタを出力します。
/* $ Revision: 1.10 $ */ /*============================================================= * revord.c * Example for illustrating how to copy the string data from * MATLAB to a C-style string and back again. * * Takes a string and returns a string in reverse order. * * This is a MEX-file for MATLAB. * Copyright (c) 1984-2000 The MathWorks, Inc. *============================================================*/ #include "mex.h" void revord(char *input_buf, int buflen, char *output_buf) { int i; /* Reverse the order of the input string. */ for(i=0;i<buflen-1;i++) *(output_buf+i) = *(input_buf+buflen-i-2); }
この例題では、ダイナミックなメモリ割り当てにCの標準関数calloc
の代わりにAPI関数mxCalloc
を使います。mxCalloc
は、MATLABのメモリマネージャを使ってダイナミックなメモリ割り当てを行い、ゼロに初期化します。Cでcalloc
を使う必要がある場合には、mxCalloc
を使わなければなりません。mxMalloc
とmxRealloc
に対しても同様です。Cでmalloc
を使う必要がある場合はmxMalloc
を使い、realloc
を使う必要がある場合はmxRealloc
を使ってください。
注意
MATLABは、MEX-ファイルを終了するときにmx 割り当てルーチン(mxCalloc , mxMalloc , mxRealloc )によって割り当てられたメモリを自動的に開放します。開放したくない場合は、API関数mexMakeMemoryPersistent を使ってください。 |
下記は、C計算ルーチンrevord
を呼び出すゲートウェイ関数です。
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { char *input_buf, *output_buf; int buflen,status; /* Check for proper number of arguments. */ if(nrhs!=1) mexErrMsgTxt("One input required."); else if(nlhs > 1) mexErrMsgTxt("Too many output arguments."); /* Input must be a string. */ if ( mxIsChar(prhs[0]) != 1) mexErrMsgTxt("Input must be a string."); /* Input must be a row vector. */ if (mxGetM(prhs[0])!=1) mexErrMsgTxt("Input must be a row vector."); /* Get the length of the input string. */ buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1; /* Allocate memory for input and output strings. */ input_buf=mxCalloc(buflen, sizeof(char)); output_buf=mxCalloc(buflen, sizeof(char)); /* Copy the string data from prhs[0] into a C string * input_ buf. * If the string array contains several rows, they are copied, * one column at a time, into one long string array. */ 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; }
ゲートウェイルーチンは、入力および出力文字列に対してメモリを割り当てます。これらはCの文字列なので、MATLAB文字列内の要素数よりも1大きい必要があります。つづいてMATLAB文字列が入力文字列にコピーされます。入力および出力文字列は、出力を反対の順番にロードする計算サブルーチン(revord
)に渡されます。mxCalloc
はメモリを0に初期化するので、出力バッファは有効なnullで終了するCの文字列であることに注意してください。API関数mxCreateString
は、Cの文字列output_buf
からMATLAB文字列を作成します。最後に、左辺出力引数plhs[0]
は、ユーザが作成したMATLAB配列に設定されます。
タイプmxArray
の変数を計算サブルーチンから分離することによって、オリジナルのCコードを大きく変更しなくてもすみます。
x = 'hello world'; y = revord(x)
The string to convert is 'hello world'. y = dlrow olleh
![]() | 第一の例 -- スカラを渡す | 複数の入出力を渡す | ![]() |