I had one structure in my code which was created with a function create_a_structure.m
with a_struct = create_a_structure()
. Several other functions either called this function, modified the values in the fields of this structure.
Using coder.cstructname(a_struct, 'a_struct')
and a few tweaks, I've managed to have Matlab coder actually create a structure named a_struct
in the generated code. Though the actual variable was named b_a_struct
, and was declared in My_project_types.h
. This made working with the generated code much easier.
Now, I wanted to add a second structure that should behave similarly, say b_struct
. Having created similar functions to work with this new structure, I was expecting that a structure named b_struct
would also be generated in the code generated by Matlab coder, but that simply is not the case.
I've since been struggling to replicate the behavior I've obtained with a_struct
.
But in short:
How to force Matlab Coder to create C structures corresponding to Matlab structs used in the Matlab code?
EDIT: Writing a header by hand is not a solution, as I'm expecting the contents of this structure to change a bit often, and I'm planning to add more structs in a similar manner.
coder.cstructname(myStructVariable, 'myStruct')
instructs MATLAB Coder to use the specified structname myStruct
as a type, basically using typedef struct {...} myStruct
.
When the generated code needs to refer to a variable with that typedef, MATLAB Coder will still need to generate some variable name that will not interfere with the type, so you may indeed see b_a_struct
as a variable name. If you keep the struct name for the type and the variable name different enough, you will likely see the expected code from the generator, e.g. when generated code with codegen -config:lib myfun -report
from:
function [v, w, x] = myfun()
%#codegen
v = struct('a',1,'b',2);
coder.cstructname(v, 'myStruct');
w = struct('a', 1, 'b', 3);
coder.cstructname(w, 'b_struct');
x = struct('a', 1, 'b', 4);
coder.cstructname(x, 'a_struct');
end
This results in something like:
void myfun(myStruct *v, b_struct *w, a_struct *x)
{
v->a = 1.0;
v->b = 2.0;
w->a = 1.0;
w->b = 3.0;
x->a = 1.0;
x->b = 4.0;
}
So indeed we see the typedefs in the input arguments as pointers and the variable names are matched (v
, w
and x
).
MATLAB Coder is quite good (sometimes quite aggressive) in optimizing generated code and its target is always to ensure the same outputs from entry-point functions given the specified inputs at codegen time. If you're calling the generated code from other C/C++ code, the actual variable names in the generated code should not be too critical, but the struct typedefs do of course really matter in interfacing between auto-generated and other code!!