Search code examples
c++cmatlabsimulinkmex

Structure as init argument in a mex file


I have a mask in simulink that has an init argument field. The init argument in my case is a structure. Now I want to use this structure in the .ccp (to make a mex file).

void init()
{
    mxArray *initarg = GetInitArg();
    ...
}

The GetInitArg() is :

#ifndef GET_INIT_ARG
#define GET_INIT_ARG

mxArray *GetInitArg() {

  return rtsys->initArg;

}

#endif

When the initarg is an int, I can call it this way in the void init():

int arg = (int)mxGetPr(initarg)[0];

Now, how would I do if initarg is a Matlab structure?

EDIT

I tried using @remus answer.

My struct look like this :

typedef struct
{
    const char *task;
    aaa_type aaa;
    bbb_type bbb;
    ccc_type ccc;
} arg_t;

The struct aaa_type, bbb_type and ccc_type are defined like this :

typedef struct
{
    double p1;
    double p2;
    double p3;
    double p4;
    double p5;
    double p6;
} aaa_type;

I try to get the init arg like this :

void init() 
{
    mxArray *initarg = GetInitArg();
    arg_t arg* = (arg_t*)mxGetPr(initarg);
    ...
}

But at the arg_t line i'm getting two compilation errors:

error C2143: syntax error : missing ';' before '*' 
error C2059: syntax error : '='

Solution

  • The list of MEX functions related to accessing structures is below:

    mxGetField
    mxSetField
    mxGetNumberOfFields
    mxGetFieldNameByNumber
    mxGetFieldNumber
    mxGetFieldByNumber
    mxSetFieldByNumber
    

    If you have a 1x1 structure, here's how you'd get one of the values:

    mxArray *field_name = mxGetField(initArg, 0, "field_name");
    

    Note that the result is another mxArray. From there you want the usual mxGetPr() for double arrays, or other mxGet... for other datatypes.

    See the MEX documentation section on C/C++ Matrix Library for API details on these functions: http://www.mathworks.com/help/matlab/cc-mx-matrix-library.html