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 everypub fnof animplblock of an interface (constructors returnSelf; methods take&self). Anasync fnis asynchronous; aResult-returning function throws its error type, aerrordomain or an untyped error (Error,String,std::io::Error, …). Anasync fnwhose last parameter is aCancelTokenis 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&TorArc<T>and returned asSelf,T, orArc<T>.error: an error domain, with a generatedDisplay(from#[weaveffi(message = "...")]templates or the variants’ docs) andstd::error::Error.callback_interface: a trait the consumer implements, accepted asArc<dyn Trait>(orOption<Arc<dyn Trait>>).custom: a type that crosses as another (its repr), converted with your functions; it may be a foreign type such asuuid::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 exportedasync 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_spawneroverrides either. Onwasm32calls are polled inline.leak-checkcounts live objects, callbacks, iterators, cancel tokens, and runs, reported by{prefix}_debug_liveso a test harness can assert a consumer released everything.anyhowlets a function returnResult<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§
- Cancel
Token - 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; pollis_cancelledonly 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 cancellableasync fn. - Error
- An untyped error that any
std::error::Errorconverts into with?. An untyped error: any failure, reported to the consumer asthrows any(code-1) with itsDisplaytext. - Foreign
Error - 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 withIter::new. An owned, type-erased iterator returned by a producer function whose IDL return type isiter<T>.
Traits§
- Spawner
- The executor hook
set_spawneraccepts. 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 + 'staticfuture aSpawnerreceives. The type-erased future aSpawnerreceives.
Attribute Macros§
- callback_
interface - Declare a callback interface: a
Send + Synctrait whose&selfmethods the consumer implements. Producers accept one asArc<dyn Trait>(orOption<Arc<dyn Trait>>). Every method returnsResult<T, E>withE: From<weaveffi::ForeignError>; whenEis 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):Tcrosses the ABI asR(bindings seeR), converted withf: fn(R) -> Result<T, E: Display>on the way in (a failure is a marshalling error carrying the message) andg: fn(&T) -> Ron the way out.Tmay be a foreign type, such asuuid::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) andstd::error::Error, unless written#[weaveffi::error(no_display)]. - export
- Export a function, or every
pub fnof an interface’simplblock. - interface
- Declare an interface: a reference-counted object type, which must be
Send + Sync. Export itsimplblock with#[weaveffi::export]. - record
- Declare a record: a struct with named fields that crosses the ABI by value (serialized in a value buffer).