Search code examples
cmatlabstructmex

MATLAB Mex: retrieving a logical from a struct in MATLAB


I have a struct created in this way:

testStruct = struct; testStruct.tf = true.

And I want to pass this struct into my c++ code through mex, this is a snapshot of what I did:

mxArray *mxValue; 
mxValue = mxGetField(prhs[0], 0, "tf");
mxLogical tf = mxGetLogicals(mxValue);
mexPrintf("tf: %i \n", tf);

Whether I set testStruct.tf to true or false, it prints tf: 1. I also tested it with an if condition and the if condition gets executed regardless of what logical I put in.

I tried bool tf = mxGetLogicals(mxValue), but that wasn't useful.

Can I get a pointer on this?


Solution

  • Can I get a pointer on this?

    ... That is kind of the problem ... mxGetLogical returns a Pointer to the first logical element in the mxArray. see documentation.

    So try this (compiled as mexTest):

    #include "mex.h"
    void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
    { 
      mxArray *mxValue; 
      mxLogical *tf;  
      mxValue = mxGetField(prhs[0], 0, "tf");
      tf = mxGetLogicals(mxValue);    
      mexPrintf("tf: %i \n", *tf);  
    }
    

    Running it gives me these resutls:

    >> testStruct.tf = true;
    >> mexTest(testStruct)
    tf: 1 
    >> testStruct.tf = false;
    >> mexTest(testStruct)
    tf: 0