| 外部インタフェース/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
| 第一の例 -- スカラを渡す | 複数の入出力を渡す | ![]() |