A.2.5 结构与 Mex-Files

在mex文件中创建结构体的基本函数是 mxCreateStructMatrix,它创建一个包含二维矩阵的结构体数组;或者使用 mxCreateStructArray

mxArray *mxCreateStructArray (int ndims, int *dims,
                               int num_keys,
                               const char **keys);
mxArray *mxCreateStructMatrix (int rows, int cols,
                                int num_keys,
                                const char **keys);

随后,可以使用 mxGetFieldmxSetField,或者使用 mxGetFieldByNumbermxSetFieldByNumber 函数来访问结构体的字段。

mxArray *mxGetField (const mxArray *ptr, mwIndex index,
                      const char *key);
mxArray *mxGetFieldByNumber (const mxArray *ptr,
                              mwIndex index, int key_num);
void mxSetField (mxArray *ptr, mwIndex index,
                  const char *key, mxArray *val);
void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
                          int key_num, mxArray *val);

oct-file 结构与 mex-file 版本之间的一个区别在于:在 mex-file 中操作结构体的函数直接包含一个 index,用于遍历按 field 组织的元素数组;而 oct-file 结构体则在每个字段中包含一个 Cell 数组。

以下文件 mystruct.c 展示了一个在 mex-file 中使用结构体的示例。

#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
              int nrhs, const mxArray *prhs[])
{
  int i;
  mwIndex j;
  mxArray *v;
  const char *keys[] = { "this", "that" };

  if (nrhs != 1 || ! mxIsStruct (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a struct");

  for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
    for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
      {
        mexPrintf ("field %s(%d) = ", mxGetFieldNameByNumber (prhs[0], i), j);
        v = mxGetFieldByNumber (prhs[0], j, i);
        mexCallMATLAB (0, NULL, 1, &v, "disp");
      }

  v = mxCreateStructMatrix (2, 2, 2, keys);

  mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
  mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
  mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
  mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
  mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
  mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
  mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
  mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));

  if (nlhs)
    plhs[0] = v;
}

以下是在 Octave 中调用此函数的示例:

a(1).f1 = "f11"; a(1).f2 = "f12";
a(2).f1 = "f21"; a(2).f2 = "f22";
b = mystruct (a);
⇒   field f1(0) = f11
    field f1(1) = f21
    field f2(0) = f12
    field f2(1) = f22
b
⇒   2x2 struct array containing the fields:

     this
     that

b(3)
⇒   scalar structure containing the fields:

     this = this3
     that = that3

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

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