Search code examples
matlabmex

My mex function ignores my if statement


I have a mex function that takes in a field of a struct in the third input (i.e. prhs[2]), which is a boolean. If true, it will parse information from the fourth input (i.e. prhs[3]). In a nutshell, this is the code excerpt:

mxValue = mxGetField(prhs[3], 0, "change"); mxLogical *change;
change = mxGetLogicals(mxValue);
mexPrintf("true/false: %i \n", *change); 
mexEvalString("drawnow;");

if ( change ) {
    mexPrintf("...Parsing info... \n");
    mexEvalString("drawnow;");
    mxValue = mxGetField(prhs[3], 0, "info");   
    nRows = mxGetM(mxValue); nCols = mxGetN(mxValue);
    Eigen::Map<Eigen::VectorXd> info((double *)mxGetPr(mxValue),nRows);

}   

As you can see, I do a printout to see whether the input prhs[2] is true or false. Even if the function prints out false, the if statement gets executed regardless, because I can see the printout ...Parsing info....

Why is my MATLAB mex function ignoring my if statement?


Solution

  • C is not MATLAB! C is C!

    You are checking if pointer change has a value. It does indeed have a value, a memory direction e.g. #72BA21, to the location where the value of the boolean is stored.

    You can either check the contents of whats inside that specific direction if(*change) as @buzjwa suggest, or grab the information on the array, instead of a pointer to it, using mxGetData.


    As a side note: learn to debug, or at least, print statements. a simple mexPrintf() call would have shown you what change contains