Is it possible to access struct fields dynamically in generated code?
Ältere Kommentare anzeigen
Hello all,
I would like to know if it is possible to access struct fields dynamically in generated code as stated in the title. For that I provide a minimum example. In my case I need to load a JSON file which is translated to a structure and I don't know the fields in advance.
%% structure.json
{
"a": 0,
"bb": 0.1,
"ccc": [],
"dddd": {},
"eeeee": "abc",
"ffffff": 'abc',
"a1": 0,
"b2": 0.1,
"c3": [],
"d4": {},
"e5": "abc",
"f6": 'abc'
}
%% main.m
structure = struct;
structure.a = 0;
structure.bb = 0.1;
structure.ccc = [];
structure.dddd = {};
structure.eeeee = 'abc';
structure.ffffff = "abc";
prototype(structure);
prototype("structure.json");
%% prototype.m
function prototype(structure)
if isstruct(structure)
field_names = fieldnames(structure);
disp("field names count: " + length(field_names));
for i = 1:length(field_names)
disp("field name " + i + ": " + field_names{i});
end
disp("content of field name a: " + structure.a);
for i = 1:length(field_names)
if ~iscell(structure.(field_names{i})) && ~isnumeric(structure.(field_names{i}))
disp("dynamic access to content of field name " + field_names{i} + ": " + structure.(field_names{i}));
end
end
elseif ischar(structure) || isstring(structure)
json_file = fileread(structure);
json_content = jsondecode(json_file);
end
end
%% compile.m
structure = struct;
structure.a = 0;
structure.bb = 0.1;
structure.ccc = [];
structure.dddd = {};
structure.eeeee = 'abc';
structure.ffffff = "abc";
structure.a1 = 0;
structure.b2 = 0.1;
structure.c3 = [];
structure.d4 = {};
structure.e5 = 'abc';
structure.f6 = "abc";
cfg = coder.config('lib');
codegen -report -config cfg prototype...
-args structure...
-O disable:inline
cfg = coder.config('exe');
codegen -report -config cfg -args structure prototype codegen/lib/prototype/examples/main.c codegen/lib/prototype/examples/main.h
Many thanks in advance,
Nikita
1 Kommentar
Joris Brouwer
am 27 Mär. 2023
I just ran into the same boundary conditions. I have a JSON input in Matlab which works perfectly with dynamic fields. Now converting to C-code I need predefined fieldnames. Since my problem is not so big (and I knew very well this was a limitation before I started but I still had a go since each version coder is improved) I'll go for the hardcoded fieldnames. Just a tit bit more coding to do.
My preferred solutions would be jsondecode (and jsonencode) to be made an extended capability C/C++ code generation. But I understand that may be though one not getting the highest priority by the development team.
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Algorithm Design Basics finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!