Skip to main content

static_init_block

Macro static_init_block 

Source
macro_rules! static_init_block {
    ($($body:tt)*) => { ... };
}
Expand description

Run code when the program or library that holds it loads, the Rust form of TVM_FFI_STATIC_INIT_BLOCK. The body is the body of a function that returns Result<()>: it registers what the library defines, such as global functions, and stops at its first error, which ? returns. A body whose statements all end in ; returns Ok(()); one that ends in an expression returns it, a Result<()>.

use tvm_ffi::{Function, Result};

fn add_one(x: i64) -> Result<i64> {
    Ok(x + 1)
}

tvm_ffi::static_init_block! {
    Function::register_global_typed("my_ext.add_one", add_one, "Add one to an integer.")?;
}

// Registered when the program loaded.
let add_one = Function::get_global("my_ext.add_one")?;
assert_eq!(i64::try_from(add_one.call_tuple((1i64,))?)?, 2);

A block runs when its program or library loads: it adds a constructor, which the loader runs, and the first constructor runs every block of the program or library, in the order of their modules and lines. Python sees what the blocks of a library registered once it loads the library, by any means, and the library stays loaded for the process, as the registrations keep its code. An error cannot reach a caller when the library loads: it is printed, and run_static_init_blocks reports it again. Where the loader does not run the constructor, call run_static_init_blocks first. A crate that a library depends on but never names is not linked into it, nor are its blocks: name it, as use my_crate as _; does.

A block runs once per process. Every library built on the crate links its own copy of the crates it uses, so a block of a crate that several libraries link is in each of them; the first library that runs it registers what it defines, and the others skip it. A block of another version of the crate, or whose text differs, is another block, and registering what it defines again is an error. A change to the body of a function the block calls does not make another block: rebuild every library that links a crate after changing it. A block is known by the module path, line, crate version and text, so two crates of the same name and version, such as plugins built from one template, share the identities of their blocks and only the first runs: give them distinct crate names.

A panic in a block is caught and reported as its error, except under panic = "abort", where it aborts the process; a failed rs_object registration is such a panic.