How C++ gets struct values from Matlab
Afficher commentaires plus anciens
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 commentaire
Réponses (2)
James Tursa
le 25 Août 2020
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);
}
Bruno Luong
le 27 Août 2020
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");
}
}
Catégories
En savoir plus sur Write C Functions Callable from MATLAB (MEX Files) dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!