| 外部インタフェース/API |
第一の例 - スカラを渡す
Cコードとその等価なMEX-ファイルの簡単な例を見てみましょう。以下は、スカラを2倍にするCの計算関数です。
#include <math.h>
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
return;
}
#include "mex.h"
/*
* timestwo.c - example found in API guide
*
* Computational function that takes a scalar and doubles it.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-2000 The MathWorks, Inc.
*/
/* $ Revision: 1.8 $ */
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
double *x,*y;
int mrows,ncols;
/* Check for proper number of arguments. */
if(nrhs!=1) {
mexErrMsgTxt("One input required.");
} else if(nlhs>1) {
mexErrMsgTxt("Too many output arguments");
}
/* The input must be a noncomplex scalar double.*/
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
!(mrows==1 && ncols==1) ) {
mexErrMsgTxt("Input must be a noncomplex scalar double.");
}
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);
/* Assign pointers to each input and output. */
x = mxGetPr(prhs[0]);
y = mxGetPr(plhs[0]);
/* Call the timestwo subroutine. */
timestwo(y,x);
}
Cでは、関数引数のチェックは、コンパイル時に行われます。MATLABでは、任意のタイプおよび数の引数をM-ファンクションに渡すことが可能で、これは引数チェックが行います。MEX-ファイルに対しても同様です。ユーザプログラムは、サポートされているタイプの入力引数または出力引数の数を安全に扱う必要があります。
この例題のソースファイルをコンパイル、リンクするには、MATLABプロンプトでつぎのようにタイプします。
mex timestwo.c
これは、実行しているプラットフォームに対応する拡張子をもつ、
timestwoというMEX-ファイルを作成するのに必要なステップを行います。timestwoはM-ファンクションのように呼び出すことができます。
x = 2;
y = timestwo(x)
y =
4
MATLABまたはオペレーティングシステムのプロンプトでMEX-ファイルを作成しコンパイルできます。MATLABは、mexスクリプトのM-ファイル版であるmex.mを使い、オペレーティングシステムはWindowsではmex.batを、UNIXではmex.shを使います。いずれの場合でも、プロンプト
mex filename
上記の例で、スカラは1行1列の行列として表されます。スカラ変数のコピーのポインタの代わりに、スカラ値を出力するmxGetScalarという特殊なAPI関数を使うことができます。以下は、そのコードです(簡潔にするため、エラーチェックは省略されています)。
#include "mex.h"
/*
* timestwoalt.c - example found in API guide
*
* Use mxGetScalar to return the values of scalars instead of
* pointers to copies of scalar variables.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-2000 The MathWorks, Inc.
*/
/* $ Revision: 1.5 $ */
void timestwo_alt(double *y, double x)
{
*y = 2.0*x;
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
double *y;
double x;
/* Create a 1-by-1 matrix for the return argument. */
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
/* Get the scalar value of the input x. */
/* Note: mxGetScalar returns a value, not a pointer. */
x = mxGetScalar(prhs[0]);
/* Assign a pointer to the output. */
y = mxGetPr(plhs[0]);
/* Call the timestwo_alt subroutine. */
timestwo_alt(y,x);
}
この例は、入力スカラxを値でサブルーチンtimestwo_altに渡しますが、出力スカラyはポインタとして渡します。
| C MEX-ファイルの例 | 文字列を渡す |