A.2.7 调用 Mex 文件中的其他函数

可以在 mex 文件中使用 mexCallMATLAB 来调用其他 Octave 函数。下面的示例展示了 mexCallMATLAB 的用法。

#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  char *str;

  mexPrintf ("Starting file myfeval.mex\n");

  mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);

  if (nrhs < 1 || ! mxIsChar (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a function name");

  str = mxArrayToString (prhs[0]);

  mexPrintf ("I'm going to call the function %s\n", str);

  if (nlhs == 0)
    nlhs = 1;  // Octave's automatic 'ans' variable

  /* Cast prhs just to get rid of 'const' qualifier and stop compile warning */
  mexCallMATLAB (nlhs, plhs, nrhs-1, (mxArray**)prhs+1, str);

  mxFree (str);
}

如果此代码位于文件 myfeval.c 中,并编译为 myfeval.mex,那么它的使用示例如下:

a = myfeval ("sin", 1)
⇒   Starting file myfeval.mex
   I have 2 inputs and 1 outputs
   I'm going to call the interpreter function sin
   a =  0.84147

请注意,在 mex 文件中无法使用函数句柄。

版权所有 © 2024-2026 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-2