Main Content

永続的な mxArray

関数 mexMakeArrayPersistent または関数 mexMakeMemoryPersistent を呼び出すことにより、MATLAB® 自動クリーンアップから配列またはメモリの一部を除外することができます。しかし、MEX 関数が永続的なオブジェクトを作成する場合、その永続的なオブジェクトが適切に破棄される前に MEX 関数がクリアされると、メモリ リークが発生する可能性があります。メモリ リークを回避するには、関数 mexAtExit を使用して、これらの関数を使用して作成されたオブジェクトのメモリを解放する関数を登録します。

次の MEX ファイル コードは永続配列を作成し、それを適切に破棄します。

#include "mex.h"

static int initialized = 0;
static mxArray *persistent_array_ptr = NULL;

void cleanup(void) {
    mexPrintf("MEX file is terminating, destroying array\n");
    mxDestroyArray(persistent_array_ptr);
}

void mexFunction(int nlhs,
    mxArray *plhs[],
    int nrhs,
    const mxArray *prhs[])
{
  if (!initialized) {
    mexPrintf("MEX file initializing, creating array\n");
        
    /* Create persistent array and register its cleanup. */
    persistent_array_ptr = mxCreateDoubleMatrix(1, 1, mxREAL);
    mexMakeArrayPersistent(persistent_array_ptr);
    mexAtExit(cleanup);
    initialized = 1;

    /* Set the data of the array to some interesting value. */
    *mxGetDoubles(persistent_array_ptr) = 1.0;
  } else {
    mexPrintf("MEX file executing; value of first array element is %g\n",
              *mxGetDoubles(persistent_array_ptr));
  }
}

参考

|

関連するトピック