How C++ gets struct values from Matlab

10 vues (au cours des 30 derniers jours)
Gummibear
Gummibear le 25 Août 2020
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
Gummibear
Gummibear le 25 Août 2020
Modifié(e) : Gummibear le 26 Août 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

Connectez-vous pour commenter.

Réponses (2)

James Tursa
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
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 Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by