Matlab API reading .mat file from c++, using STL container

前端 未结 3 1861
予麋鹿
予麋鹿 2020-12-05 08:58

I have to read some .mat data files from c++, I read through the documentation, but I would like to know how to handle the data in a clean and elegant way, e.g. using std:ve

3条回答
  •  独厮守ぢ
    2020-12-05 09:21

    Here's another idea. If you're allergic to bare pointers in C++ code (nothing wrong with them, by the way), you could wrap the bare pointer in a boost or C++11 smart pointer with a deleter that calls the correct mxDestroyArray() when the pointer goes out of scope. That way you don't need a copy, nor does your user code need to know how to correctly deallocate.

    typedef shared_ptr mxSmartPtr;
    
    mxSmartPtr readMATarray(MATFile *pmat, const char *varname)
    {
        mxSmartPtr pdata(matGetVariable(pmat, varname),
                         mxDestroyArray);  // set deleter
        return pdata;
    }
    
    int some_function() {
        mxSmartPtr pdata = readMATarray(pmat, "LocalDouble");
        ...
        // pdata goes out of scope, and mxDestroy automatically called
    }
    

    Idea taken from here: http://www.boost.org/doc/libs/1_56_0/libs/smart_ptr/sp_techniques.html#incomplete

提交回复
热议问题