Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Getting Started

This guide builds a small Rust library, generates bindings for it, and calls it from C and from Python. A second, shorter path at the end starts from an IDL instead and implements the generated C header in C. The code on this page is the examples/getting-started crate and the examples/idl/greeter project, which the workspace’s tests build and call.

Install the CLI

You need a stable Rust toolchain. Install the weaveffi CLI from crates.io (or grab a prebuilt binary with cargo binstall weaveffi-cli):

cargo install weaveffi-cli
weaveffi --version

Write the producer

Create a library crate and add the weaveffi crate. It needs no crate-type: WeaveFFI builds the C dynamic library itself (with cargo rustc --crate-type cdylib).

cargo new --lib mathlib
cd mathlib
cargo add weaveffi

Replace src/lib.rs with this. Everything here is safe Rust; the attributes write the extern "C" layer.

/// Errors the math functions report.
#[weaveffi::error]
#[derive(Debug)]
pub enum MathError {
    /// division by zero
    DivisionByZero = 1,
}

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

/// Divide `a` by `b`, failing when `b` is zero.
#[weaveffi::export]
pub fn div(a: i32, b: i32) -> Result<i32, MathError> {
    a.checked_div(b).ok_or(MathError::DivisionByZero)
}

/// Greet someone by name.
#[weaveffi::export]
pub fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}

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

A few things to notice:

  • Every C symbol starts with the crate’s name, so this crate exports mathlib_add, mathlib_div, and mathlib_greet, plus the runtime (mathlib_error_clear, mathlib_run_free, and so on). A library is one namespace, so a symbol is the prefix and the item’s name, wherever in the crate the item is declared.
  • Result<i32, MathError> makes div throw the MathError domain. The enum’s discriminants are the stable error codes, and the macro generates its Display from each variant’s doc comment (or a #[weaveffi(message = "...")] template), which is the message consumers see. A Result whose error type is an untyped error (String, std::io::Error, weaveffi::Error) works too: it throws a message without a code to match on.
  • weaveffi::export_runtime!() appears exactly once, at the crate root.

The producer macro guide covers records, enums, objects, callbacks, iterators, async functions, and custom types.

Configure and generate

Run weaveffi init in the crate. It writes a weaveffi.toml whose [project] table points at the crate itself, then lists anything the crate still needs (the weaveffi dependency, an exported item, the export_runtime! call):

weaveffi init

The file it writes generates the C header and the Python package; edit targets to pick the languages you ship (without it, every target is generated):

[project]
input = "."
out = "bindings"
targets = ["c", "python"]

Generate the bindings. With a [project] table, weaveffi generate needs no arguments and works from any directory in the project:

weaveffi generate

weaveffi generate builds the library with Cargo’s dev profile (pass --profile <name> for another, and -F/--features for Cargo features), then reads the API from the library it built: the attributes embed a description of every exported declaration in the library, so the bindings match the compiled code exactly, #[cfg] included. weaveffi extract prints that description as an IDL.

The output has one directory per target: the C target writes bindings/c/mathlib.h, and the Python target writes an installable package named mathlib. Run weaveffi generate again after any change: it rewrites only the files whose contents changed and removes files a previous run wrote that it no longer produces, using the generation records it keeps in bindings/.weaveffi/ (commit them with the bindings).

Call it from C

The header is the contract every other binding is built on. Each value is one C value: a string is a mathlib_run (a pointer and a byte length, never NUL-terminated), every call overwrites a mathlib_error the caller provides, and a returned run is released with mathlib_run_free:

/* A C consumer of the getting-started library, built against the generated
   header (bindings/c/mathlib.h). */
#include <stdio.h>
#include <string.h>
#include "mathlib.h"

int main(void) {
    /* Refuse a library built from different source than the header. */
    if (mathlib_abi_version() != MATHLIB_ABI_VERSION || mathlib_contract_check() != NULL) {
        fprintf(stderr, "mathlib.h doesn't match the loaded library\n");
        return 1;
    }

    mathlib_error err; /* every call overwrites it */
    printf("2 + 3 = %d\n", mathlib_add(2, 3, &err));

    mathlib_div(1, 0, &err);
    if (err.code == mathlib_MathError_DivisionByZero) {
        printf("error %d: %.*s\n", err.code, (int)err.message_len, (const char*)err.message_ptr);
        mathlib_error_clear(&err);
    }

    /* A string crosses as a run: its UTF-8 bytes and their length, no NUL. */
    const char* name = "C";
    mathlib_run arg = {(const uint8_t*)name, strlen(name)};
    mathlib_run greeting = mathlib_greet(arg, &err);
    printf("%.*s\n", (int)greeting.len, (const char*)greeting.ptr);
    mathlib_run_free(greeting);
    return 0;
}

Build it against the library weaveffi generate built:

cc -I bindings/c main.c -L target/debug -lmathlib -o main
DYLD_LIBRARY_PATH=target/debug ./main    # LD_LIBRARY_PATH on Linux
2 + 3 = 5
error 1: division by zero
Hello, C!

The first check is the one every generated binding makes for you when it loads the library: mathlib_abi_version() must equal the header’s MATHLIB_ABI_VERSION, and mathlib_contract_check() returns the name of the first declaration the library has changed since the header was generated, or NULL. Errors and Memory states every ownership rule the generated bindings follow for you.

Call it from Python

While you iterate, run weaveffi generate --dev: it generates as usual, then copies the library it built into the generated packages that look for a bundled copy (the Python package does) and prints how the other targets find it. Then install the package:

weaveffi generate --dev
pip install ./bindings/python
import mathlib

print(mathlib.add(2, 3))          # 5
print(mathlib.greet("Python"))    # Hello, Python!

try:
    mathlib.div(1, 0)
except mathlib.MathError as e:
    print(e)                      # (1) division by zero

On import the package checks the library’s ABI revision and every declaration’s contract, so a library built from incompatible source fails to load with an error naming the declaration that’s missing or changed. To load a library from somewhere else, set MATHLIB_LIBRARY to its full path; every target that loads the library at run time honors that {PREFIX}_LIBRARY variable. The Python page documents the generated surface.

Ship it

weaveffi package --target python

weaveffi package builds the library in release mode for this machine (that’s weaveffi build), then writes installable artifacts to dist/: here a wheel with the library inside, which needs neither MATHLIB_LIBRARY nor a compiler:

pip install dist/python/mathlib-*.whl

Packaging covers more platforms (iOS, Android, Windows, wasm32), every target’s artifacts, and publishing.

Implementing an IDL in C

A producer doesn’t have to be Rust. Start from an IDL, generate the C header, and implement it in any language that can export C symbols. Outside a Rust crate, weaveffi init writes a starter IDL and a weaveffi.toml:

mkdir greeter && cd greeter
weaveffi init           # writes greeter.yml and weaveffi.toml

Edit greeter.yml to declare the API (the IDL reference has the full schema):

# yaml-language-server: $schema=https://weaveffi.com/weaveffi.schema.json
version: "0.13.0"
doc: A greeter implemented in C.
functions:
  - name: add
    doc: Add two integers, wrapping on overflow.
    params:
      - { name: a, type: i32 }
      - { name: b, type: i32 }
    return: i32
  - name: greet
    doc: Greet someone by name.
    params:
      - { name: name, type: string }
    return: string

For an IDL the identity comes from [package] in weaveffi.toml, so the prefix and the library are both greeter:

[project]
input = "greeter.yml"
out = "bindings"
targets = ["c", "python"]

[package]
name = "greeter"
version = "0.1.0"

Generate the header and implement it:

weaveffi generate --target c     # writes bindings/c/greeter.h

The API’s own functions come first. GREETER_DEFINE_CONTRACT defines every contract function with the hashes the header was generated with, and a synchronous function stores a cleared error in out_err on success:

/* One contract function per declaration, as the header computed them. */
GREETER_DEFINE_CONTRACT

int32_t greeter_add(int32_t a, int32_t b, greeter_error* out_err) {
    memset(out_err, 0, sizeof *out_err); /* success: a cleared error */
    return (int32_t)((uint32_t)a + (uint32_t)b);
}

greeter_run greeter_greet(greeter_run name, greeter_error* out_err) {
    memset(out_err, 0, sizeof *out_err);
    static const char hello[] = "Hello, ";
    size_t len = sizeof hello - 1 + name.len + 1;
    uint8_t* text = greeter_alloc(len); /* the consumer frees it with greeter_run_free */
    if (text == NULL) {
        static const char oom[] = "out of memory";
        greeter_error_set(out_err, -1, (const uint8_t*)oom, sizeof oom - 1);
        greeter_run none = {NULL, 0};
        return none;
    }
    memcpy(text, hello, sizeof hello - 1);
    if (name.len != 0) memcpy(text + sizeof hello - 1, name.ptr, name.len);
    text[len - 1] = '!';
    greeter_run out = {text, len};
    return out;
}

Every producer also exports the runtime surface: the ABI revision, one allocator for every run it hands out (8-aligned, released by its own run_free), the error helpers, cancel tokens, and the leak counter:

/* The runtime surface every producer exports. */
uint32_t greeter_abi_version(void) { return GREETER_ABI_VERSION; }

/* One allocator for every run: returned strings and buffers, error messages
   and payloads, and runs a consumer allocates. calloc's alignment is at
   least 8 on every supported platform. */
uint8_t* greeter_alloc(size_t len) { return len != 0 ? calloc(len, 1) : NULL; }
void greeter_run_free(greeter_run run) { free((void*)run.ptr); }

static const uint8_t* copy(const uint8_t* ptr, size_t len) {
    uint8_t* run = greeter_alloc(len);
    if (run != NULL) memcpy(run, ptr, len);
    return run;
}

void greeter_error_clear(greeter_error* err) {
    if (err == NULL) return;
    free((void*)err->message_ptr);
    free((void*)err->payload_ptr);
    memset(err, 0, sizeof *err);
}

void greeter_error_free(greeter_error* err) {
    greeter_error_clear(err);
    free(err);
}

void greeter_error_set(greeter_error* err, int32_t code, const uint8_t* message_ptr,
                       size_t message_len) {
    if (err == NULL) return;
    greeter_error_clear(err);
    err->code = code;
    if (message_ptr != NULL && message_len != 0) {
        err->message_ptr = copy(message_ptr, message_len);
        err->message_len = err->message_ptr != NULL ? message_len : 0;
    }
}

void greeter_error_set_payload(greeter_error* err, const uint8_t* ptr, size_t len) {
    if (err == NULL) return;
    free((void*)err->payload_ptr);
    err->payload_ptr = ptr != NULL && len != 0 ? copy(ptr, len) : NULL;
    err->payload_len = err->payload_ptr != NULL ? len : 0;
}

/* Cancel tokens (this API has no async functions, but every library exports
   the same runtime surface). */
struct greeter_cancel_token {
    atomic_int refs;
    atomic_bool cancelled;
};

greeter_cancel_token* greeter_cancel_token_create(void) {
    greeter_cancel_token* token = malloc(sizeof *token);
    if (token != NULL) {
        atomic_init(&token->refs, 1);
        atomic_init(&token->cancelled, false);
    }
    return token;
}

void greeter_cancel_token_cancel(greeter_cancel_token* token) {
    if (token != NULL) atomic_store(&token->cancelled, true);
}

bool greeter_cancel_token_is_cancelled(const greeter_cancel_token* token) {
    return token != NULL && atomic_load(&((greeter_cancel_token*)token)->cancelled);
}

void greeter_cancel_token_destroy(greeter_cancel_token* token) {
    if (token != NULL && atomic_fetch_sub(&token->refs, 1) == 1) free(token);
}

/* Leak counters: kind -1 is 0 because this producer doesn't count. */
uint64_t greeter_debug_live(int32_t kind) {
    (void)kind;
    return 0;
}

The C ABI contract lists what a hand-written producer owes its consumers, including honoring a vtable’s GREETER_VTABLE_THREAD_AFFINE flag once the API has callbacks. Build it as libgreeter.so (libgreeter.dylib on macOS, greeter.dll on Windows). The file defines GREETER_BUILD before it includes the header, so the header’s GREETER_API exports the symbols on Windows too:

cc -shared -fPIC -I bindings/c greeter.c -o libgreeter.so

Then run weaveffi generate for the other targets; they load it exactly as they load a Rust producer. From Python, for example:

weaveffi generate --target python
pip install ./bindings/python
GREETER_LIBRARY=$PWD/libgreeter.so python3 -c "import greeter; print(greeter.add(2, 3))"   # 5

Next steps

  • Project Configuration: [package] metadata, [build] settings, per-target options, and how regeneration cleans up stale files.
  • Packaging: building every platform and publishing the artifacts.
  • Samples and Examples: the tested example crates, and three complete producers from the minimal calculator to the feature-complete kvstore.
  • Generators: what each language gets.
  • Gate CI on weaveffi generate --check so committed bindings can’t drift; see Stability and Versioning.