Dynamic function call using eval
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I know that using eval() is typically discouraged, but I was wondering if it can be safely used to dynamically execute functions with similar names. For example, let's say that I have a function (tested on r2023b):
function y = foo(x,N)
switch(N)
case 8
y = uint8(x);
case 16
y = uint16(x);
case 32
y = uint32(x);
case 64
y = uint64(x);
% ... and so on
otherwise
error('Invalid N.');
end
end
This can be rewritten more compactly by using eval as:
function y = foo(x,N)
if ~ismember(N,2.^(3:6)) % :7, :8, etc
error('Invalid N.');
end
eval(sprintf('y = uint%d(x)',N));
end
Again, I know that eval() is generally frowned upon. However, I was wondering what can be the drawbacks in this case. So far, I can think of two:
- eval() calls are generally slower than calling a function directly per se, and in this case there would be also the overhead of sprintf(), so latency probably increases.
- Code Analyzer can't tell that x is being used and y is being set, so I don't know if I'm missing any kind of optimization performed by Matlab during code execution.
Are there any other massive drawbacks I'm missing? Or, conversely, are there smarter ways to your knowledge to compactly write and perform this kind of operations in similar contexts?
1 commentaire
Stephen23
le 21 Mar 2024
"Or, conversely, are there smarter ways to your knowledge to compactly write and perform this kind of operations in similar contexts? "
FEVAL
Réponses (2)
Voss
le 21 Mar 2024
Déplacé(e) : Voss
le 21 Mar 2024
"compactly write and perform this kind of operations [without using eval]"
function y = foo(x,N)
[ism,idx] = ismember(N,[8,16,32,64]);
if ~ism
error('Invalid N.');
end
f = {@uint8,@uint16,@uint32,@uint64};
% f = arrayfun(@str2func,"uint"+[8,16,32,64],'UniformOutput',false); % alternative
y = f{idx}(x);
end
Steven Lord
le 21 Mar 2024
x = 42;
for n = 3:6
bitlength = 2^n;
fprintf("Casting %d to int%d.\n", x, bitlength)
y = cast(x, "int" + bitlength)
end
In general, the eval function allows arbitrary code execution. Therefore you need to implicitly trust the user of your function not to do something malicious. Your use of ismember in this case is a good first step, but that's easy to get around. Let's say N is an instance of a class that overloads ismember to return true in cases like this. It could also overload sprintf to create "y = uint8(x); DROP TABLE Students --" as the string that gets passed to eval.
eval("y = uint8(42); disp('I could have written anything here'); y = uint8(x)")
In this case, N is effectively '8(42); disp('I could have written anything here'); y = uint8'
0 commentaires
Voir également
Catégories
En savoir plus sur Data Type Identification dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!