Sridutt
Sridutt

Reputation: 382

Access Matlab Struct from mex

I have a Structure from Matlab passed to mex. It is passed correctly, I verified it with mxGetClassName(mxArray_pointer_carrying_struct) which returns struct as the class type. The struct has 15 fields n corresponding properties, all 30 Strings (15 property_names, 15 property_values).

I am able to access property names using mxGetFieldNameByNumber(mxArray_pointer_carrying_struct, index);

How can I access the property values?

The code I have to do above looks as below:

extract_settings(const mxArray *p)
{
    mwIndex j = 1;
    const char *property;
    mexPrintf("\nInput Arg %i is of type:%s\n",j,mxGetClassName(p));
    for(int i = 0;i<=14;i++)
    {
        property = mxGetFieldNameByNumber(p, i);  %gets property names
        mexPrintf("%s-- \n",property); %Displays 15 property names
    }
}

My struct Looks as below :

{ 
TRIGGER_POLARITY : LEVEL_LOW
EDGE : EDGE_RISING 
. 
.
. (15 elements as of now)
}

Upvotes: 2

Views: 3764

Answers (1)

Florian Brucker
Florian Brucker

Reputation: 10355

You're probably looking for mxGetFieldByNumber. There's also a full example for passing structs to MEX files shipped with MATLAB, see this documentation from Mathworks. You can load the example in MATLAB as follows:

edit([matlabroot '/extern/examples/refbook/phonebook.c']);

EDIT: There's also mxGetField which lets you access the field using its name.

EDIT2: To convert the result from mxGetField to a C string you can use mxArrayToString. Note that you need to free the string's memory after you have used it. You can use mxIsChar to check whether the field contains a MATLAB character array.

Upvotes: 5

Related Questions