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

Gummibear
Gummibear 2020년 8월 25일
편집: Gummibear 2020년 8월 26일
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

댓글을 달려면 로그인하십시오.

답변 (2개)

James Tursa
James Tursa 2020년 8월 25일

0 개 추천

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 2020년 8월 27일

0 개 추천

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");
}
}

카테고리

도움말 센터File Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

제품

릴리스

R2018b

태그

질문:

2020년 8월 25일

답변:

2020년 8월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by