Skip to main content

Crate weaveffi

Crate weaveffi 

Source
Expand description

WeaveFFI: write safe Rust, get a stable C ABI and bindings for 11 languages.

This is the one crate a Rust producer depends on. Tag the items you want to export, anywhere in the crate, and call export_runtime! once at the crate root. Every expansion emits the extern "C" functions the generated bindings call, marshalling each value through the audited runtime, so you never write unsafe glue. Every C symbol starts with the crate’s name (calculator_add below).

ⓘ
/// The library's error domain. Its `Display` comes from the docs.
#[weaveffi::error]
#[derive(Debug)]
pub enum MathError {
    /// division by zero
    DivisionByZero = 1,
}

/// Add two integers.
#[weaveffi::export]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// Divide, reporting division by zero through the ABI's error channel.
#[weaveffi::export]
pub fn div(a: i32, b: i32) -> Result<i32, MathError> {
    a.checked_div(b).ok_or(MathError::DivisionByZero)
}

/// Parse an integer; any error converts into `weaveffi::Error`
/// (`throws any`).
#[weaveffi::export]
pub fn parse(text: &str) -> Result<i64, weaveffi::Error> {
    Ok(text.parse()?)
}

// The runtime symbols (memory, errors, cancel tokens), once per crate.
weaveffi::export_runtime!();

The attributes also embed the API in the built library, which is what weaveffi generate reads to emit the header and bindings, so the producer and the bindings can’t drift: the bindings describe exactly what the library was compiled with. A library is one namespace: every exported name is unique across the crate.

§What you get

  • export: export a free function, or every pub fn of an impl block of an interface (constructors return Self; methods take &self). An async fn is asynchronous; a Result-returning function throws its error type, a error domain or an untyped error (Error, String, std::io::Error, …). An async fn whose last parameter is a CancelToken is cancellable.
  • record: a struct crossing by value.
  • enumeration: a C-style enum, or one with data-carrying variants.
  • interface: a reference-counted object type, passed as &T or Arc<T> and returned as Self, T, or Arc<T>.
  • error: an error domain, with a generated Display (from #[weaveffi(message = "...")] templates or the variants’ docs) and std::error::Error.
  • callback_interface: a trait the consumer implements, accepted as Arc<dyn Trait> (or Option<Arc<dyn Trait>>).
  • custom: a type that crosses as another (its repr), converted with your functions; it may be a foreign type such as uuid::Uuid.
  • set_spawner: install the executor async exports run on.
  • export_runtime!: the runtime symbols and the crate’s tag type, once, at the crate root.

§Features

  • tokio (default) runs exported async fns on Tokio: the current runtime when a launcher is called from inside one, otherwise a multi-thread runtime created on first use. Without it, each async call runs on a thread of its own. set_spawner overrides either. On wasm32 calls are polled inline.
  • leak-check counts live objects, callbacks, iterators, cancel tokens, and runs, reported by {prefix}_debug_live so a test harness can assert a consumer released everything.
  • anyhow lets a function return Result<T, anyhow::Error>.

Macros§

export_runtime
Emit the runtime symbols every WeaveFFI library exports, prefixed with the crate’s name ({prefix}_abi_version, {prefix}_error_set, {prefix}_error_set_payload, {prefix}_error_clear, {prefix}_error_free, {prefix}_alloc, {prefix}_run_free, the four {prefix}_cancel_token_* functions, and {prefix}_debug_live), and the crate’s tag type. Invoke it exactly once, at the crate root.

Structs§

CancelToken
The producer’s handle on a consumer’s cancel token, the final parameter of a cancellable async fn. When the consumer cancels, the runtime drops the function’s future and completes the call with the cancelled code; poll is_cancelled only for cooperative cleanup (work on other threads, say). The producer’s handle on a consumer’s cancel token, accepted as the final parameter of a cancellable async fn.
Error
An untyped error that any std::error::Error converts into with ?. An untyped error: any failure, reported to the consumer as throws any (code -1) with its Display text.
ForeignError
A consumer’s callback-interface implementation failed. A callback method’s error type converts from it (E: From<ForeignError>), and it’s a valid error type itself. A failure a consumer’s callback-interface implementation reported, or a value it returned that the producer couldn’t accept.
Iter
An owned, lazily pulled iterator, returned by a function whose bindings see iter<T>. Build one from any iterator with Iter::new. An owned, type-erased iterator returned by a producer function whose IDL return type is iter<T>.

Traits§

Spawner
The executor hook set_spawner accepts. An executor hook that drives the futures produced by async exports.

Functions§

set_spawner
Install the process-wide executor exported async fns run on. Call it once at startup, before the first async export is launched. Install the process-wide spawner async exports run on.

Type Aliases§

BoxFuture
The type-erased Send + 'static future a Spawner receives. The type-erased future a Spawner receives.

Attribute Macros§

callback_interface
Declare a callback interface: a Send + Sync trait whose &self methods the consumer implements. Producers accept one as Arc<dyn Trait> (or Option<Arc<dyn Trait>>). Every method returns Result<T, E> with E: From<weaveffi::ForeignError>; when E is a #[weaveffi::error] domain, the consumer’s typed errors arrive as its variants.
custom
Declare a custom type, #[weaveffi::custom(repr = R, lift = f, lower = g)] pub type Name = T; (or on a struct): T crosses the ABI as R (bindings see R), converted with f: fn(R) -> Result<T, E: Display> on the way in (a failure is a marshalling error carrying the message) and g: fn(&T) -> R on the way out. T may be a foreign type, such as uuid::Uuid.
enumeration
Declare an enum: C-style (every variant a unit, crossing as an int32_t) or rich (variants with named fields, crossing as a value buffer). A variant’s discriminant is its = value, or one more than the previous variant’s.
error
Declare an error domain from an enum whose variants have explicit positive values (the stable codes) and optional named fields (the code’s payload). The macro generates Display (each variant’s #[weaveffi(message = "...")] template, which may name its fields in braces, else the first line of its docs) and std::error::Error, unless written #[weaveffi::error(no_display)].
export
Export a function, or every pub fn of an interface’s impl block.
interface
Declare an interface: a reference-counted object type, which must be Send + Sync. Export its impl block with #[weaveffi::export].
record
Declare a record: a struct with named fields that crosses the ABI by value (serialized in a value buffer).