Dynamic function call using eval

14 visualizaciones (últimos 30 días)
jackphen
jackphen el 21 de Mzo. de 2024
Respondida: Steven Lord el 21 de Mzo. de 2024
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 comentario
Stephen23
Stephen23 el 21 de Mzo. de 2024
"Or, conversely, are there smarter ways to your knowledge to compactly write and perform this kind of operations in similar contexts? "
FEVAL

Iniciar sesión para comentar.

Respuestas (2)

Voss
Voss el 21 de Mzo. de 2024
Movida: Voss el 21 de Mzo. de 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
  2 comentarios
jackphen
jackphen el 21 de Mzo. de 2024
I had not thought of arrayfun together with str2func! It sure provides the same flexibility as the sprintf() in eval without the need for the eval() call. Thanks!
Voss
Voss el 21 de Mzo. de 2024
Editada: Voss el 21 de Mzo. de 2024
You're welcome!
Here is another alternative, using Stephen23's suggestion of feval:
function y = foo(x,N)
b = [8,16,32,64];
[ism,idx] = ismember(N,b);
if ~ism
error('Invalid N.');
end
y = feval("uint"+b(idx),x);
end

Iniciar sesión para comentar.


Steven Lord
Steven Lord el 21 de Mzo. de 2024
For this case, use the cast function.
x = 42;
for n = 3:6
bitlength = 2^n;
fprintf("Casting %d to int%d.\n", x, bitlength)
y = cast(x, "int" + bitlength)
end
Casting 42 to int8.
y = int8 42
Casting 42 to int16.
y = int16 42
Casting 42 to int32.
y = int32 42
Casting 42 to int64.
y = int64 42
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)")
I could have written anything here
y = uint8 42
In this case, N is effectively '8(42); disp('I could have written anything here'); y = uint8'

Categorías

Más información sobre Data Type Identification en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by