Transmit a Structure from MATLAB to C

1 回表示 (過去 30 日間)
Ziyu Hua
Ziyu Hua 2022 年 1 月 19 日
コメント済み: James Tursa 2022 年 1 月 19 日
Hello everyone. I want to transmit a MATLAB structure to C. Like:
a.para1=1;
a.para2=2;
...
In my C code, I want to use these parameters to do my futher work. The current code I used is
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
double *pointerlhs, *pointerrhs[2]; /* pointer to real data in new array */
mwSize index;
/* Check for proper number of arguments. */
if (nrhs != 1) {
mexErrMsgTxt("This function takes one input arguments.");
}
/* Create an m-by-n mxArray; you will copy existing data into it */
plhs[0] = mxCreateNumericMatrix(1, 2, mxDOUBLE_CLASS, mxREAL);
//pointerrhs[1] = mxGetPr(prhs[0]);
pointerlhs = mxGetPr(plhs[0]);
/* Copy data into the mxArray */
for (index = 0; index < 2; index++) {
pointerrhs[index]= mxGetPr(prhs[index]);
pointerlhs[index] = *pointerrhs[index];
}
return;
}
which meed to tramsmit the value of the structure one by one like:
Transmit_Function(a.para1,a.para2...)
How can I get all parameters in a structure while just use one input in my MATLAB code. Like:
Transmic_Function(a)
Then I can get and use all the paramters in a.
Thanks.

採用された回答

Ziyu Hua
Ziyu Hua 2022 年 1 月 19 日
This can be realized by MATALB C API function "mxGetField"
#if !defined(_WIN32)
#define dgesv dgesv_
#endif
#include "mex.h"
#include"matrix.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (mxIsStruct(prhs[0]))
{
double *pointer, *pointerrhs;
mxArray *StructValue = mxGetField(prhs[0], 0, "a");
plhs[0] = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL);
pointer = mxGetPr(plhs[0]);
pointer[0] = *(mxGetPr(StructValue));
}
else
{
mexErrMsgTxt("The Input is Not a Struct");
}
}
  1 件のコメント
James Tursa
James Tursa 2022 年 1 月 19 日
This will not work. The variable name is "a", but the field names are "para1" and "para2". You need to use the field names in your mxGetField( ) call, not "a". Also your code is overly complicated and does not contain argument checking so it will crash with invalid inputs.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by