nk 1.0.0
C++ Numerical Computing Runtime
Loading...
Searching...
No Matches
fn_handle.hpp
1// core/include/nk/value/fn_handle.hpp
2//
3// nk::FnHandle — the canonical MATLAB-style callback type used by
4// the numerical-library API for any function that takes a
5// user-supplied function handle (fzero, integral, fminsearch,
6// cellfun, structfun, …).
7//
8// Signature mirrors what MATLAB function handles are at the engine
9// boundary: variadic Value inputs, caller-allocated Value outputs.
10// `outs.size()` plays the role of MATLAB's `nargout`.
11//
12// Library-side example:
13// Value fzero(FnHandle fn, double x0, mr);
14//
15// User-side (C++):
16// auto root = fzero(
17// [](auto args, auto outs, auto *mr) {
18// double x = args[0].toScalar();
19// outs[0] = Value::scalar(x*x - 2.0, mr); // honour caller mr
20// },
21// /*x0=*/1.0, mr);
22//
23// Engine-adapter side (toolboxes/optim/src/local/fzero.cpp):
24// void fzero_reg(args, nargout, outs, ctx) {
25// auto handle = args[0];
26// auto cb = [&ctx, &handle](Span<const Value> a, Span<Value> o,
27// std::pmr::memory_resource * /*mr*/) {
28// // Engine allocates results; library caller absorbs them
29// // via move-assign into o, so mr is unused on this side.
30// auto r = ctx.engine->callFunctionHandleMulti(handle, a, o.size());
31// for (size_t i = 0; i < o.size() && i < r.size(); ++i)
32// o[i] = std::move(r[i]);
33// };
34// outs[0] = fzero(cb, args[1], ctx.engine->resource());
35// }
36
37#pragma once
38
39#include <memory_resource>
40
41#include <nk/value/function_ref.hpp>
42#include <nk/value/span.hpp>
43#include <nk/value/value.hpp>
44
45namespace nk {
46
54using FnHandle = function_ref<void(Span<const Value> args,
55 Span<Value> outs,
56 std::pmr::memory_resource * mr)>;
57
58} // namespace nk