Home > Mobile >  Simple mex file crash?
Simple mex file crash?

Time:03-24

I am learning mex files in matlab. I have written this simple code

#include "mex.h"

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

    double *outData, *inData;

    if(nrhs!=2) mexErrMsgTxt("Missing input data.");

    inData = mxGetDoubles(prhs[0]);
    outData = mxGetDoubles(plhs[0]);
    
    outData[0] =  inData[0] inData[1];
}

But when I try to run it, matlab crashes. The problem is the last line, have you any suggestions why?

Thank you

CodePudding user response:

plhs[0] (i.e. the pointer left hand side of you function call) is the output.

This output variable is not allocated in memory, you just have a pointer to it. So you can not write on it (nor read from it) without creating it first.

So you would need something like

const int ndims = 1; // or whatever dims you want
const mwSize dims[]={1}; // or whatever size you want

// create memory/variable 
plhs[0] = mxCreateNumericArray(ndims ,dims,mxDOUBLE_CLASS,mxREAL);
// now it exists
outData = mxGetDoubles(plhs[0])

However, note that if you don't input a 2 length array, inData[1] will not exist, thus causing a RuntimeError, which crashes MATLAB. So its generally good practice to check the length of the array before accessing it.

  • Related