cscript-ffi 0.3.0

Loads and calls user-supplied, dynamically-linked C blocks (Declarations/StartFcn/OutputFcn code slots, one instance's state per block) -- the one place in this workspace where unsafe FFI into arbitrary native code is deliberately allowed, kept isolated from every other crate.
Documentation

Loads a user-supplied, precompiled shared library (.so/.dylib/.dll) exposing three C functions and calls into it once per block instance per transient step — a dynamically- loaded, stateful escape hatch for block behavior no existing continuous-blocks block covers, the same role a code-generation/scripting slot plays in other block-diagram simulation tools' own extensibility mechanisms, or an ngspice XSPICE codemodel .cm plugin (see an internal gotcha note on ngspice XSPICE codemodels needing MFBINIT set in the environment, for that already-used pattern).

This crate is the one place in this workspace where calling into arbitrary native code is deliberately allowed. Loading a shared library and calling into it is unsafe by construction: the code runs in-process with this program's own privileges, can corrupt memory, crash the process, or do anything a normal native program can do. That is an accepted, bounded risk of this specific opt-in feature (a user explicitly names a .so file in their own netlist), not something this crate tries to sandbox away — no different in kind from the XSPICE codemodel pattern already used elsewhere in this same project.

The C-side contract

A block's shared library must export:

// Called once, when this block instance is created. Return an opaque instance-state
// pointer (typically malloc'd), or NULL if this block instance carries no state at all.
void *cscript_start(void);

// Called once per resolved transient step. `state` is whatever cscript_start() returned
// for this instance (NULL if none); `in`/`in_len` is this step's input vector, in the
// netlist's own declared order; `dt` is this step's size (seconds) -- needed for any block
// that integrates over time, e.g. `state->integral += error * dt`, the same explicit-Euler
// update every other stateful block in this project already uses; `out`/`out_len` is the
// output vector to fill.
void cscript_output(void *state, const double *in, int in_len, double dt, double *out, int out_len);

// Optional. Called once when this block instance is dropped. Free anything
// cscript_start() allocated. If the symbol is absent, `state` is simply leaked -- harmless
// for a short-lived CLI run, but real cleanup is provided for any longer-lived host.
void cscript_free(void *state);

// Optional. Return a deep copy of `state` (independent memory: mutating the copy through
// future cscript_output() calls must never affect the original, and vice versa). Only
// needed to use this block under general-simulator's adaptive step-size control, which retries a
// rejected trial step from an independent copy of every block's state -- see "Adaptive
// step-size control and instance cloning" below.
void *cscript_clone(void *state);

The optional continuous-state (xc) contract

A block declaring xc_count > 0 in its netlist line owns a continuous-state vector the solver itself numerically integrates (RK4, one independent integration per block, the same convention [continuous_blocks::StateSpace::rk4_step] uses for every other dynamic block in this workspace) -- as opposed to the plain void *state blob above, which is never touched by anything but the block's own C code. This is a pure vector-field evaluation the solver calls, not something the block's own cscript_output hand-integrates itself (a block that wants to manage its own state by hand, e.g. a hand-rolled dv/dt Euler estimate, remains exactly as correct as before this contract existed -- this new contract is specifically for state the solver should own instead).

Such a block exports two more functions instead of cscript_output (never both -- [CScriptRegistry::instantiate_xc] requires exactly these two, [CScriptRegistry::instantiate] requires plain cscript_output; a library is meant to implement one contract or the other):

// Pure vector-field evaluation: dxc/dt = f(t, u, xc, xd). Must not
// mutate `state`, `in`, or `xc` -- called up to four times per accepted step (RK4's own
// k1..k4 stages), including from now-discarded trial steps under adaptive stepping (see
// "Adaptive step-size control and instance cloning" below -- the same "a rejected trial's
// mutation never survives" guarantee applies here, so this restriction is about correctness
// of a single RK4 step's own math, not about adaptive-step safety).
void cscript_derivative(void *state, const double *in, int in_len,
                        const double *xc, int xc_len, double *xc_dot, int xc_dot_len);

// Used instead of cscript_output. Identical role, with read access to this step's own
// already-RK4-integrated xc (the *new*, post-step continuous state -- matching every other
// dynamic block's own "step state, then compute output from the new state" convention). May
// still mutate `state` for its own xd/bookkeeping purposes, exactly like plain
// cscript_output.
void cscript_output_xc(void *state, const double *in, int in_len, double dt,
                       const double *xc, int xc_len, double *out, int out_len);

xc itself lives in dae-runtime's own BlockState, not inside the opaque void *state blob -- the one place this contract breaks the "everything is opaque to Rust" rule, and deliberately so: the solver's own RK4 stepper needs to do ordinary vector arithmetic on it between stages, which an opaque C-managed blob could never allow. cscript_start/ cscript_free/cscript_clone are unaffected either way -- xc's own initial value is always the zero vector (matching every other dynamic block's own "starts at rest" convention), and cloning it is a plain Vec<f64> clone, needing no C-side involvement at all.

The optional discrete-state update function

cscript_output/cscript_output_xc are permitted to mutate state themselves (documented above) -- fine for the common case, but it conflates two different things: computing this step's output from the block's current state, and committing that state forward to the next step. Some block-diagram tools' own code-block feature keeps these deliberately separate (an output function that's expected to be side-effect-free, plus a dedicated update function that's the only place discrete state actually advances) -- cscript now offers the same split, as an entirely optional third function:

// Optional. Called once per resolved (or per-sample-period, under ts=) step, immediately
// after cscript_output/cscript_output_xc for that same call -- the dedicated place to
// commit `state`'s own discrete bookkeeping forward to the next step, instead of doing it
// inside the output function itself. `xc` is this step's own already-integrated continuous
// state (`xc_len == 0` for a block with `xc_count == 0`, exactly like every other xc-aware
// parameter in this contract). If this symbol is absent, a cscript block is expected to
// keep updating `state` directly inside cscript_output/cscript_output_xc, exactly as before
// this function existed -- nothing about the existing contract changes if you never add
// this.
void cscript_update(void *state, const double *in, int in_len, double dt,
                     const double *xc, int xc_len);

The optional block-controlled sample time

A cscript block's own ts=/freq= fixes a period at netlist-parse time — the right choice for a controller running at a genuinely fixed rate. Some blocks instead know their own next execution time only at runtime (a modulator whose next switching instant depends on a live computation, an event-driven controller that only needs to re-run when something crosses a threshold). ts=variable in the netlist selects this mode, and requires the library to export one more function (checked once, up front, the same "checked once, up front" discipline cscript_clone's own adaptive-stepping requirement already uses):

// Required when this block declares ts=variable (never called otherwise). Called
// immediately after cscript_output/cscript_output_xc on every step this block actually
// ran. Returns the number of seconds, *relative to this call*, until this block should
// next be executed -- not an absolute time, consistent with every other cscript function
// never seeing absolute time either. Must return a value > 0; dae-runtime holds this
// block's last output constant (zero-order hold) for that many seconds, then calls
// cscript_output/cscript_output_xc again and asks for the next interval once more.
double cscript_next_sample_hit(void *state, const double *in, int in_len,
                                const double *xc, int xc_len);

Unlike the discrete-state update function above, this one is genuinely required once opted into via ts=variable — a missing symbol is a load-time error (CScriptError::MissingSymbol), not a silent no-op, since there would otherwise be no way to ever know when to run the block at all.

Adaptive step-size control and instance cloning

general-simulator's adaptive step-size control retries a rejected trial step from scratch: every block's state is cloned before the trial, the trial runs against the clone, and if rejected the clone is discarded and a fresh one is taken for the next, smaller attempt -- never mutating the real, confirmed state until a trial is actually accepted. That is exactly correct for plain Rust block state (a Vec<f64> clone is a real, independent copy), but a [CScriptInstance]'s state is an opaque pointer this crate never reads through, so it cannot generically deep-copy it -- only the user's own C code knows its own layout. [Clone] for [CScriptInstance] is implemented in terms of cscript_clone for exactly this reason, and panics if the library didn't export it. In practice this should never fire: check [CScriptInstance::supports_clone] once, up front, and refuse adaptive step-size control for a netlist containing a cscript block whose library doesn't support it, the same way dae-runtime already does before entering its own adaptive loop.

Everything else in the user's .c file — includes, #defines, typedefs, file-scope static helper functions and variables the user wants visible to all three of the functions above for one translation unit — needs no special support from this crate: plain C file scope already provides exactly that. The user compiles their own .c file into a shared library themselves (e.g. cc -shared -fPIC -o my_block.so my_block.c); this crate never invokes a compiler.

in_len/out_len must match the netlist's own declared input/output counts for this block — nothing in this crate checks that they do; a mismatch is a plain out-of-bounds C array access, same as it would be calling OutputSignal(9, 0) past a declared output count in any other tool's own code-slot mechanism. This is documented, not enforced.

Multi-instance state

Two block instances naming the same lib= path share one loaded image (dlopen on most platforms de-duplicates repeat loads of the same path — see [CScriptLibrary::load]), but each instance gets its own cscript_start() call and its own returned state pointer, so per-instance state (e.g. an integrator's accumulator) is never accidentally shared between two uses of the same block in one netlist. [CScriptRegistry] caches loaded libraries by path for exactly this reason: cheap repeat instantiation, without repeat dlopen.