What is the proper syntax for feeding a C struct (defined in a header file) to a MATLAB function?

조회 수: 26 (최근 30일)
SUMMARY: With MATLAB Coder, what is the proper syntax for passing a C struct (defined in a header file) to a MATLAB function?
  1. define a C struct in a header file,
  2. defined a MATLAB equivalent of the struct with coder.typeof commands, and finally
  3. link the two types of structs with a coder.cstructname command.
I want to use a C main function to
  1. create an instance of a C struct (that is defined in a header file, say mystruct.h) and
  2. feed that struct to a MATLAB function (defined in an m-file, say foo.m, containing a %#codegen notification).
  • Suppose p is an instance of the C struct.
  • Suppose also that main.c has #include "mystruct.h".
  • Suppose that the main C function calls foo with foo(p);.
If the struct class T is defined by defining the individual fields and ending with
T = coder.cstructname(T,'mystruct','extern','HeaderFile','mystruct.h');
will MATLAB Coder infer the correct input type for foo with the following sequence of commands for code generation?
cfg = coder.config('exe')
cfg.CustomSource = 'main.c'
cfg.CustomInclude = 'mystruct.h'
codegen -config cfg foo -args {T}

채택된 답변

Darshan Ramakant Bhat
Darshan Ramakant Bhat 2020년 11월 18일
You are almost there. I just want to clarify few things.
Let's say that the struct that you have difined looked like below :
typedef struct {
double f1;
float f2;
} mycstruct;
Then you have do like below in MATLAB Coder
>> T.f1 = 0;
>> T.f2 = single(0);
>> T1 = coder.cstructname(T,'mycstruct','extern','HeaderFile','myheader.h');
>> T1
T1 =
coder.StructType
HeaderFile: myheader.h
1×1 extern mycstruct struct
f1: 1×1 double
f2: 1×1 single
Edit Type Object
Like the last line you can display the variable in MATLAB to make sure that the coder.type object created is proper.
You can use the "T1" to define the argument type in MATLAB Coder
cfg = coder.config('exe')
cfg.CustomSource = 'main.c'
cfg.CustomInclude = 'myheader.h'
codegen -config cfg foo -args {T1}
  댓글 수: 1
Joe M
Joe M 2020년 11월 21일
@10535214: Thank you for answering.
I found that my header file also needed to have #ifndef, #define, and #endif statements in order to avoid code generation failure due to multiple definitions of the struct.
Is there any way to feed argv from a C main function directly to a function defined in an m-file? If so, how would I specify the type of that variable? I suspect that parsing command-line input would be easier with MATLAB than with C.

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

추가 답변 (0개)

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by