How C++ gets struct values from Matlab

9 ビュー (過去 30 日間)
Gummibear
Gummibear 2020 年 8 月 25 日
回答済み: Bruno Luong 2020 年 8 月 27 日
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 日
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 日
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");
}
}

カテゴリ

Help Center および File ExchangeWrite C Functions Callable from MATLAB (MEX Files) についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by