How C++ gets struct values from Matlab

Does anybody knows how to get a Matlab struct values(string, matrix, double, bool,...) into c++? There is a example in Matlab "phonebook.c" which shows how to do that.
In this example, the output are direct saved in a Matlab cell with the functions mxCreateCellArray(), mxSetCell() etc.
What I want to do is save the values in two vectors in C++. I tried with mxGetField() and mxGetFieldByNumber() to get the values and push them into a vector. But I can only get the pointer of them with the type mxArray. And I used mexPrintf() to show them in Matlab, it looks like
PS. I don't why, when I wrote a * before the pointer, it's wrong.
Thanks a lot.

1 Commento

Gummibear
Gummibear il 25 Ago 2020
Modificato: Gummibear il 26 Ago 2020
I found the solution to get the double values. The key point is I have to use the function mxGetPr() to get the pointer of a mxArray. For example, to get the phone number "3386":
mxArray *phoneNum;
phoneNum = mxGetField(prhs[0], 0, "phone"); // 3386
double *number;
number = mxGetPr(phoneNum);
mexPrintf("...%f = ", *number);
BUT there is still a problem, the return value of the mxGetPr() is double, I don't konw how to get the names (string) of the 1. field? Can anyone help?
Thanks

Accedi per commentare.

Risposte (2)

Looks like your strings are char type and not the newer string type. So you can try the following:
mxArray *mx;
char *name;
mx = mxGetField( prhs[0], 0, "name" );
if( mx && mxIsChar(mx) ) {
name = mxArrayToString( mx );
mexPrintf("name = %s\n",name);
mxFree(name);
}
For char array
#include "mex.h"
/* File test.c mex file demo access to a string of s.name
*
* >> mex test.c
* >> s = struct('name','Jordan Robert')
* >> test(s)
* */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxArray *FieldName;
#define MAX_LENGTH 100
char Cname[MAX_LENGTH];
int lgt;
if (nrhs<1)
mexPrintf("need 1 argument\n");
else
{
FieldName = mxGetField(prhs[0], 0, "name");
if (FieldName)
{
lgt = mxGetN(FieldName);
lgt++;
if (lgt <= MAX_LENGTH)
if (mxGetString(FieldName, Cname, lgt)==0)
mexPrintf("name is \"%s\"\n", Cname);
else mexPrintf("mxGetString fails\n");
else mexPrintf("Buffer too small\n");
}
else mexPrintf("field 'name' not exists\n");
}
}

Categorie

Prodotti

Release

R2018b

Richiesto:

il 25 Ago 2020

Risposto:

il 27 Ago 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by