Next: Calling External Code from Oct-Files, Previous: Accessing Global Variables in Oct-Files, Up: Oct-Files [Contents][Index]
There is often a need to be able to call another Octave function from within an
oct-file, and there are many examples of such within Octave itself. For
example, the quad
function is an oct-file that calculates the definite
integral by quadrature over a user-supplied function.
There are also many ways in which a function could be given as input. It might be passed as one of
The code below demonstrates all four methods of passing a function to an oct-file.
#include <octave/oct.h> #include <octave/parse.h> DEFMETHOD_DLD (funcdemo, interp, args, nargout, "Function Demo") { int nargin = args.length (); if (nargin < 2) print_usage (); octave_value_list newargs; for (octave_idx_type i = nargin - 1; i > 0; i--) newargs(i-1) = args(i); octave_value_list retval; if (args(0).is_function_handle () || args(0).is_inline_function () || args(0).is_string ()) retval = interp.feval (args(0), newargs, nargout); else error ("funcdemo: INPUT must be string, inline, or function handle"); return retval; }
The first input to the demonstration code is a user-supplied function and the remaining arguments are all passed to the function.
funcdemo (@sin, 1) ⇒ 0.84147 funcdemo (@(x) sin (x), 1) ⇒ 0.84147 funcdemo ("sin", 1) ⇒ 0.84147 funcdemo (@atan2, 1, 1) ⇒ 0.78540
When the user function is passed as a string the treatment of the function is
different. In some cases it is necessary to have the user supplied function as
an octave_function
object. In that case the string argument can be used
to create a temporary function as demonstrated below.
std::octave fcn_name = unique_symbol_name ("__fcn__"); std::string fcode = "function y = "; fcode.append (fcn_name); fcode.append ("(x) y = "); fcn = extract_function (args(0), "funcdemo", fcn_name, fcode, "; endfunction"); … if (fcn_name.length ()) clear_function (fcn_name);
There are two important things to know in this case. First, the number of input arguments to the user function is fixed, and in the above example is a single argument. Second, to avoid leaving the temporary function in the Octave symbol table it should be cleared after use. Also, by convention all internal function names begin and end with the character sequence ‘__’.
Next: Calling External Code from Oct-Files, Previous: Accessing Global Variables in Oct-Files, Up: Oct-Files [Contents][Index]