c++matlabmex

Converting a C++ library into MATLAB mex


I have a big C++ code and I want to integrate this into MATLAB so that I can use it inside my matlab code. If it was a single code making its mex file would have been the best option. But since now it's a code that needs to be compiled and built in order to run, I don't know how can I use the functions in this code.
Is making mex files for the whole code the only option or is there any other workaround? Also I would like some help on how can I make mex files for the whole code and then build it.

For more insight, this is the code I am trying to integrate in matlab http://graphics.stanford.edu/projects/drf/densecrf_v_2_2.zip . Thank You!


Solution

  • First you'll need to compile the library (either static or dynamically linked). Here are the steps I took on my Windows machine (I have Visual Studio 2013 as C++ compiler):

    Next modify the example file dense_inference.cpp to make it a MEX-function. We'll replace the main function with:

    void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    {
    ..
    }
    

    and instead of receiving arguments in argc/argv, we'll obtain the parameters from the input mxArray. So something like:

    if (nrhs<3 || nlhs>0)
        mexErrMsgIdAndTxt("mex:error", "Wrong number of arguments");
    
    if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[1]) || !mxIsChar(prhs[2]))
        mexErrMsgIdAndTxt("mex:error", "Expects string arguments");
    
    char *filename = mxArrayToString(prhs[0]);
    unsigned char * im = readPPM(filename, W, H );
    mxFree(filename);
    
    //... same for the other input arguments
    // The example receives three arguments: input image, annotation image,
    // and output image, all specified as image file names.
    
    // also replace all error message and "return" exit points
    // by using "mexErrMsgIdAndTxt" to indicate an error
    

    Finally, we compile the modified MEX-file (place the compiled LIB in the same example folder):

    >> mex -largeArrayDims dense_inference.cpp util.cpp -I. -I../include densecrf.lib
    

    Now we call the MEX-function from inside MATLAB:

    >> dense_inference im1.ppm anno1.ppm out.ppm
    

    The resulting segmented image:

    out.ppm