如何释放由mxGetData()

时间:2017-02-28 23:03:03

标签: c++ matlab mex

我正在将mat文件导入我的C ++代码。导入数据后,执行计算并保存到另一个地方,我想释放原始数据占用的内存。

是否有任何特定功能可以执行此操作。只是删除mxGetData()返回的指针释放内存吗?

这是我创建的用于导入mat文件的类

#ifndef READMAT_H
#define READMAT_H
#include "mat.h"
#include "matrix.h"
#include "mex.h"
#include "program_exception.h"
#include "stdint.h"

class readmat
{
private:
    const size_t *dimarray;
    const char **dir;
    MATFile *pmat;
    int ndir;
    mxArray *painfo,*pa;
    const char *file;
    int minute;
    int second;
    const char *name;
    const char *name1;
    bool isdouble;
    no_mat_exception noMAT;
public:

    //with default value
    readmat(const char *f);
    //  get number of dimensions
    int getnumbrofdimensions() const;
    // get pointer to array
    void*  getarraypointer() const;
    // get pointer to each dimension size
    const size_t* dimensionpointer() const;
    //number of elements
    int numberofelements() const;
    ~readmat();

};

#endif

以下是cpp实现

#include "readmat.h"
#include <iostream>
#include "mat.h"
#include "matrix.h"
#include "mex.h"
using namespace std;

// set the file name
readmat::readmat(const char *f)
{
    file = f;
    pmat = matOpen(file, "r");
    if (pmat == NULL) {
        throw noMAT;
    }
    else
    {
        dir = (const char **)matGetDir(pmat, &ndir);
        if (dir == NULL) {
            printf("Error reading directory of file %s\n", file);

        }
        else if (ndir > 1)
        {
            cout << "The number of variables are larger than 1" << endl;
        }
        else
        {
            mxFree(dir);
            matClose(pmat);
            pmat = matOpen(file, "r");
            if (pmat == NULL) {
                throw noMAT;
            }
            else
            {
                painfo = matGetNextVariableInfo(pmat, &name);
                matClose(pmat);
            }
            pmat = matOpen(file, "r");
            if (pmat == NULL) {
                throw noMAT;
            }
            else
            {
                pa = matGetNextVariable(pmat, &name1);
                matClose(pmat);
            }
        }

    }

}



int readmat::getnumbrofdimensions() const
{

    return mxGetNumberOfDimensions(painfo);
}

void* readmat::getarraypointer() const
{
    //return mxGetPr(pa);
    return mxGetData(pa);
}

const size_t*  readmat::dimensionpointer() const
{
    return mxGetDimensions(painfo);
}

int readmat::numberofelements() const
{
    return mxGetNumberOfElements(painfo);
}
readmat::~readmat()
{
    mxFree(pa);
    mxFree(painfo);

}

此处,当我删除对象程序时触发文件 free.c 中的断点。

2 个答案:

答案 0 :(得分:3)

edit([matlabroot '/extern/examples/eng_mat/matdgns.c']);上的MATLAB演示似乎建议使用mxDestroyArray代替mxFree

答案 1 :(得分:1)

调用mxGetData()时。函数唯一能做的就是返回一个指针,指向存储在mxArray中的真实数据(与虚数相反)。

因此不需要释放内存,因为在此调用期间没有动态分配任何内容。