External Crate Bindings

A rust""" block is convenient for a screenful of Rust. Beyond that, Rust code is more comfortable in a crate: a directory with its own manifest, source files, tests and editor support. @rust_crate binds such a crate to Julia. You mark the functions and types to expose with #[julia], and RustCall builds the crate and generates a Julia module for it, much as maturin does for Python.

This page starts with a walkthrough that assumes no Rust experience, then describes how to ship a crate inside a Julia package, and ends with reference material on what #[julia] accepts.

If you want to…Read
bind your first crateYour first crate
know what a crate item becomes in JuliaWhat you get in Julia
put a crate in a Julia packagePrecompilation Support
edit Rust and see the change without restarting JuliaHot Reload
look up a rule or an error messageThe #[julia] attribute in detail and the sections after it

Inline block or crate?

rust""" blockCrate + @rust_crate
Where the Rust livesin a Julia stringin .rs files, with Cargo.toml
Editor support (rust-analyzer), cargo test, cargo docnoyes
Dependenciesa // cargo-deps: comment[dependencies] in Cargo.toml
Several source files and modulesnoyes
Generic functions and structs, instantiated on demandyesno (concrete items only)
Usable from Python or other Rust code toonoyes

Both can be used in the same Julia module.

Your first crate

1. Create the crate

A crate is a directory containing a manifest, Cargo.toml, and a source tree whose root for a library is src/lib.rs:

my_math/
├── Cargo.toml
└── src/
    └── lib.rs

If you have Rust installed, cargo new --lib my_math creates this layout. Otherwise create the two files by hand; there is nothing else to it.

2. Cargo.toml

Cargo.toml plays the role of Julia's Project.toml:

[package]
name = "my_math"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
rustcall_julia_macros = "0.7"
  • [package] names the crate. edition selects the language edition; 2021 is a good default.
  • crate-type = ["cdylib"] asks for a C-compatible shared library (.so, .dylib or .dll), which is what Julia loads. If you leave this section out, RustCall builds a small wrapper crate around yours instead, so it still works, but Hot Reload needs the cdylib form.
  • rustcall_julia_macros is the crate that provides the #[julia] attribute. It is published on crates.io. When you work from a checkout of RustCall.jl, point at its copy instead: rustcall_julia_macros = { path = "/path/to/RustCall.jl/deps/rustcall_julia_macros" }.

3. src/lib.rs

use rustcall_julia_macros::julia;

#[julia]
fn factorial(n: u64) -> u64 {
    (1..=n).product()
}

#[julia]
fn mean(xs: &[f64]) -> Option<f64> {
    if xs.is_empty() {
        None
    } else {
        Some(xs.iter().sum::<f64>() / xs.len() as f64)
    }
}

#[julia]
pub struct Point {
    pub x: f64,
    pub y: f64,
}

#[julia]
impl Point {
    #[julia]
    pub fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }

    #[julia]
    pub fn distance(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }

    #[julia]
    pub fn describe(&self) -> String {
        format!("({}, {})", self.x, self.y)
    }
}
  • use rustcall_julia_macros::julia; brings the attribute into scope, like using Package: name in Julia.
  • Everything marked #[julia] is exposed. Anything else stays private to the crate. For a struct's methods, mark the impl block and each method you want to expose.
  • The code is ordinary Rust. You can add #[test] functions and call factorial from other Rust code as usual.

4. Load it from Julia

using RustCall

const MyMath = @rust_crate "/path/to/my_math"

MyMath.factorial(10)                # => 0x0000000000375f00  (3628800 as a UInt64)
MyMath.mean([1.0, 2.0, 3.0])        # => RustCall.RustOption{Float64}(true, 2.0)

p = MyMath.Point(3.0, 4.0)          # calls Point::new
MyMath.distance(p)                  # => 5.0
MyMath.describe(p)                  # => "(3, 4)"
p.x                                 # => 3.0
p.x = 6.0                           # fields are assignable
propertynames(p)                    # => (:x, :y)

The first call to @rust_crate builds the crate with Cargo, which downloads its dependencies once and can take a minute. The compiled library is cached: loading the same sources again, in this or a later session, does not rebuild. Edit a source file and the next @rust_crate rebuilds.

RustCall builds into its own cache directory, not into my_math/target/, so it does not interfere with your own cargo build or cargo test.

Inside a function or another local scope, use the value the macro returns:

function load_my_math(crate_path)
    bindings = @rust_crate crate_path
    return bindings.factorial(5)
end

5. Check the interface without building

Before a long build, or when a binding you expected is missing, boundary_report lists every position RustCall looked at and anything it cannot bind, and builds nothing:

RustCall.boundary_report("/path/to/my_math")
# RustCall boundary report for crate /path/to/my_math: no unsupported positions (10 checked).

RustCall.scan_crate(path) returns the same information as data.

What you get in Julia

@rust_crate returns a bindings object whose properties are the generated functions and types. Rust names are kept.

In the crateIn Julia
#[julia] fn f(a: i32) -> i32MyMath.f(a); arguments are converted as for an inline #[julia] function
#[julia] pub struct Pointthe type MyMath.Point, a handle to a Rust-owned value
fn new(...) -> Self in a #[julia] implthe constructor MyMath.Point(...)
a method taking &self or &mut selfMyMath.method(obj, args...)
a function in the impl without selfa static method, called with the type first: MyMath.name(MyMath.Point, args...) (Static methods)
a pub field of a supported typeobj.field, readable and assignable
a function in #[julia] mod geometryMyMath.geometry.f(...): one Julia submodule per Rust module
Result<T, E>, Option<T> returnRustCall.RustResult{T, E}, RustCall.RustOption{T}

The types that may appear in a signature are the same as for inline blocks: integers, floats, bool, char, &str, String, numeric slices &[T] / &mut [T], Result, Option, extern "C" fn callbacks, raw pointers, and #[julia] structs by reference. The FFI Type Contract is the authoritative list. A signature that uses anything else is reported by boundary_report and refused when the bindings are generated; see Unsupported types in a crate.

A Rust value handed to Julia is owned by its Julia wrapper and dropped when that wrapper is garbage collected (Object lifetime). A panic in a #[julia] item is caught and raised as RustCall.RustPanicError.

Options of @rust_crate

const B = @rust_crate "/path/to/crate" release=false features=["simd"]
OptionDefaultMeaning
release=true/falsetrueBuild optimized (--release) or in Cargo's debug profile. Debug builds compile faster and run slower.
features=["a", "b"]noneCargo features of the crate to enable. Features are Rust's compile-time switches, declared under [features] in Cargo.toml.
default_features=falsetrueTurn the crate's default feature set off.
cache=true/falsetrueReuse a previously built library.
name="Mod"crate nameName of the generated module. Defines nothing in the calling module.
submodule="Mod"noneDefine the generated module under that name in the calling module, so using .Mod: f works. The form to use in a package.
pyo3_host=truefalseBind a PyO3 crate through a live Python interpreter; see PyO3 Crates.

The #[julia] attribute in detail

The rest of this page is reference material. It is precise rather than introductory, and you do not need it to get started.

What the attribute generates

#[julia] is additive. Your item is left exactly as you wrote it, so other Rust code, tests and other attribute macros still see a normal function or impl block. Next to it the attribute emits a C-ABI wrapper under a derived symbol name, and Julia calls that wrapper:

#[julia]
fn add(a: i32, b: i32) -> i32 {
    a + b
}

// …is kept as written, and this is added beside it (simplified):
#[no_mangle]
pub extern "C" fn rustcall_add(a: i32, b: i32) -> i32 {
    /* call add(a, b) inside a panic boundary */
}

What makes a Rust function callable from another language explains #[no_mangle] and extern "C", and How RustCall Calls Rust shows the full generated code.

For a struct:

#[julia]
pub struct Point {
    pub x: f64,
    pub y: f64,
}

the attribute makes the struct pub and #[repr(C)] and generates

  • Point_free(ptr), the destructor Julia's finalizer calls;
  • Point_get_x(ptr) / Point_set_x(ptr, value) and the same for y, which back p.x and p.x = … in Julia.

A field's own #[cfg] gates its accessors too, on top of the struct's: a #[cfg(target_os = "linux")] field has no Point_get_* elsewhere.

Generic items are refused

An extern "C" entry point needs concrete types, and #[julia] sees one item and cannot know which instantiations Julia will call. A #[julia] function, struct, impl block or method with a type or const parameter, or with impl Trait in its signature, is therefore a compile error at the item:

error: #[julia] function `identity` is generic over `T`: an `extern "C"` entry point
       needs concrete types, ...

Write a non-generic #[julia] item that calls the generic one (#[julia] fn identity_i32(x: i32) -> i32 { identity(x) }), or define the code in a rust""" block, where RustCall monomorphizes generic functions and structs on demand (see Generics). Lifetime parameters are fine: fn echo<'a>(s: &'a str) -> &'a str is wrapped as usual.

For Impl Blocks

#[julia]
impl Counter {
    #[julia]
    pub fn new(initial: i32) -> Self {
        Self { value: initial }
    }

    #[julia]
    pub fn get(&self) -> i32 {
        self.value
    }
}

#[julia] is additive (#279): the impl block above is left exactly as written — Counter::new and Counter::get keep their Rust signatures for other callers, #[test]s and other proc-macros — and the FFI wrappers are emitted next to it under rustcall_-prefixed symbols:

  • rustcall_Counter_new(initial) - Returns *mut Counter
  • rustcall_Counter_get(ptr) - Takes *const Counter, returns i32

The generated Julia bindings keep the Rust names (Counter(1), get(c)); they resolve the exported symbol through the manifest, so nothing in the Julia API changes.

The Rust shim also chooses its argument and temporary bindings so they do not hide the native function or its inputs. For example, a parameter named callback in fn callback(callback: extern "C" fn() -> i32) -> i32 keeps its original name and signature in Rust source and manifest metadata; only the shim's private binding changes. Pointer/length lowering and the panic-boundary guard obey the same rule. Native item lookup remains lexical, preserving function-local annotated items and qualified external targets without forcing every call through a self:: path.

The impl block may live in any module of the crate, not only next to the struct: #[julia] impl crate::Counter { ... } in src/ops.rs, impl super::Counter from a child module, or use crate::Counter; #[julia] impl Counter all bind their methods to Counter (#315). The method symbols follow the struct the header names (rustcall_Counter_get), never the module the block was written in, so the header has to spell the struct's path the way the proc-macro reads it: crate::… and super::… as written, a bare name as the block's own #[julia] module path. A block whose header names no #[julia] struct — or one whose symbols the proc-macro would qualify differently, such as a bare impl Counter inside a #[julia] mod for a struct at the crate root — fails the scan with the header to write instead of silently binding nothing. A header that resolves to a struct without #[julia] — a plain struct Counter declared beside the block, which is what Rust itself resolves to — fails the same way rather than attaching to a same-named annotated struct elsewhere: annotate that struct, or spell the intended one (impl crate::Counter).

A file reached only by a literal include!("api.rs") is scanned too: its items are compiled into the including module, so that is where they bind — the #[julia] mod chain included — so a fragment included inside #[julia] pub mod ops gets ops-qualified symbols. An include whose path is not a literal (include!(concat!(env!("OUT_DIR"), "/api.rs"))) names a file the build writes later and is left to the compiler, as is a fragment that is not a list of items (include!("table.rs") holding [1, 2, 3]).

A fragment may declare out-of-line modules of its own, and those are followed (#343). Their files are resolved against the fragment's directory, which is what rustc does: with include!("frag/api.rs") in src/lib.rs and pub mod nested; inside api.rs, the module's file is src/frag/nested.rs — not src/nested.rs — even though nested is a child of the including module. A declaration whose file does not exist is noted and skipped, exactly as a missing mod target elsewhere in the tree.

Inline blocks: the wrapper is emitted where the block is

A rust""" block follows the same rule (#342): the wrappers of a method whose impl sits in another module than its struct are emitted inside that module, so a signature may name a type only that module can see (type Count = i32; beside the block). The exported symbol is crate-global and still follows the struct (rustcall_Counter_get), so nothing on the Julia side changes. Such a wrapper declares string buffers of its own (Counter_label_RustCallOwnedString) rather than sharing the struct's, the way a crate's wrappers always have; the manifest states which buffer each method uses, so both flavours resolve the right <owner>_free_rust_string. Julia still binds a method only when it can map every type its signature names, so a method returning a module-local alias compiles on the Rust side but has no Julia wrapper until the alias is spelled as a type RustCall knows.

Borrowed owners imported through module globs

Required &Owner and &mut Owner arguments use checked opaque handles when RustCall can prove that the type names a concrete #[julia] owner. Inline owners selected with #[derive(JuliaStruct)] retain the same checked shared and mutable borrow contract. That proof also follows scoped module glob imports, including an unambiguous use super::* in a separate impl module:

// src/operations.rs; Counter and Destination are annotated in the parent.
use super::*;
#[julia]
impl Destination {
    #[julia]
    pub fn read(&mut self, source: &Counter) -> i32 {
        self.value = source.value;
        self.value
    }
}

Julia passes its Counter handle directly. The manifest carries the proven owner identity in Arg.handle, with Arg.abi = "handle" or "handle_mut"; expression and written bindings consume that same metadata. Existing type, liveness, library-image, call-scoped rooting and mutable-alias checks remain in force. A glob import does not weaken any of those checks.

Resolution is conservative and scoped. Local declarations and explicit named imports take precedence within Rust's type namespace. Imports that supply only a function, constant or static value do not hide a type supplied by a glob. RustCall follows each applicable glob's actual module scope and reexports for the requested identifier, including aliases of crate, self and super and subsequent glob imports, accounting for plain types and aliases as well as annotated owners. Private and public glob candidates compete in their defining scope before outward visibility is applied. Hidden ambiguity is conservatively refused, even when Rust can expose only a value under that imported name and obtain its type from another glob. Use an unambiguous qualified path to the concrete annotated owner in that case. RustCall accepts a unique proven owner; it never selects a type merely because it is the only same-named annotated struct anywhere in the crate. Conflicting candidates, unknown scopes or cycles without a unique proof remain unsupported. A plain local type or alias cannot be bypassed to reach a same-named owner elsewhere. Generated public string-buffer and Result/Option aggregate types retain their actual visibility in this lookup; importing one never selects an unrelated annotated owner of the same name. These helper types are not opaque owners. Semantic lookup also applies Rust's raw-identifier and Unicode NFC identity rules, so an equivalent spelling cannot bypass a local shadow. A type alias is deliberately not expanded into an owner proof: use the concrete annotated type path instead; its diagnostic names the alias-specific limitation. This includes an alias whose Rust target is an annotated owner.

Unexpanded macro invocations, includes, and attributes or derives that could introduce a sibling shadow make glob inference conservative. A named import or qualified owner path helps only when the binding itself can be proved. An opaque rewriting attribute on a module or file makes its contents and all descendants unprovable, including local and qualified owner references, imports from outside, and Self arguments. Use expanded Rust source whose owner boundary can be proved; another import cannot repair this uncertainty. Build configuration matters too: cfg decisions resolved by the selected build can remove inactive bindings and prove the remaining scope, while unknown conditional declarations/imports remain a reason to refuse the proof. Unprefixed import roots follow the Rust edition (crate-root imports in 2015, lexical imports from 2018 onward); ordinary type paths retain lexical lookup.

For a borrowed argument whose owner cannot be proved, the manifest records Arg.abi = "borrow_unresolved" and a borrow_reason. Passing a generated handle then reports an unsupported borrowed-owner boundary with that reason, rather than suggesting a by-value layout registration. Use an explicit import or a qualified path to identify the intended annotated owner:

use super::{Counter, Destination};
use rustcall_julia_macros::julia;
// Alternatively spell the argument as `source: &crate::Counter`.

Do not register an opaque owner's layout by value to repair a borrow. Required borrowed positions retain the explicit Ptr{Cvoid} escape, including when their owner is unresolved. It remains unchecked: the caller must validate pointee layout, lifetime, library generation and aliasing and keep the storage alive. Normal generated owner handles need no raw pointers for an unambiguous scoped glob.

The same scoped identity proof selects optional borrowed owners and explicit rustcall_owned_return owners. Their separate argument/return ABI, lifetime proofs and producer-marker checks still apply. Proven optional Julia argument positions accept a correctly typed owner or nothing, never a raw pointer. Unsupported owner resolution does not provide a raw-pointer escape for an optional position.

Optional borrowed owners

A non-generic #[julia] function or method can accept an optional borrow of a concrete #[julia] owner. Julia passes that owner's generated handle or nothing:

#[julia]
pub fn compute(
    source: &Matrix,
    scratch: &mut Scratch,
    team: Option<&Team>,
) -> Result<(), String> {
    // Application-specific work; None can select the sequential path.
    Ok(())
}
bindings.compute(source, scratch, nothing)
bindings.compute(source, scratch, team)

Option<&mut Owner> is supported with the same checks and exclusive-borrow rules. This applies to free functions, static methods and receiver methods, including Option<&Self> when the pointee is the enclosing annotated owner. The application decides what an absent argument means; RustCall supplies no scheduling or numerical policy.

The manifest identifies the concrete owner through Arg.handle and records Arg.abi = "handle_optional" or "handle_optional_mut". Those values state optionality and shared/mutable access explicitly. The C representation is one nullable thin pointer (*const Owner or *mut Owner): the generated shim reconstructs None from null and a call-scoped Some(&Owner) or Some(&mut Owner) from a non-null pointer. Rust's native Option/niche layout never crosses the ABI. A producer exports <symbol>_optional_owner_ptr_v1; bindings require that marker before calling an optional-owner shim, so an older producer cannot be called using the new argument shape. Rebuild the crate and regenerate bindings when the marker is missing.

nothing is the only ordinary Julia spelling of absence. A freed handle, closed-image handle, wrong owner type or malformed value is an error, never None. Optional positions reject every Ptr value, including C_NULL; they also reject Some(handle) and missing. Pass the correctly typed handle directly. Required &Owner/&mut Owner arguments retain their existing ABI and explicit raw-pointer escape hatch.

Every present owner is checked against the library image of the resolved call, including a receiver and required arguments. An owner from a retired image is rejected when the call targets a replacement image; merely having all the old owners agree with one another is insufficient. nothing has no image and is excluded from those comparisons. Present owners remain rooted for the entire call. A mutable borrow may not alias any other present borrow of the same owner, including a receiver, a required argument or another optional argument. Shared/shared aliasing is allowed, and absent arguments borrow nothing. Optional owners can be combined with required owners and numeric slices in one signature. Present optional owners participate in the same image and borrow-overlap checks; nothing contributes no owner image or memory span. A wrapper using both optional owners and slices requires both contracts' producer markers on the captured library image.

Only borrows whose lifetimes end with this synchronous call are supported. Static or escaping references, nested optional forms, unannotated pointee types, type- or const-generic signatures and asynchronous functions are refused with a diagnostic. An optional-owner wrapper also cannot return a nonstatic borrowed &str view, whether its lifetime is named or elided; return an owned String or an explicit &'static str instead. Use a concrete annotated adapter for unsupported forms. Owner resolution must be provable from the scanned Rust syntax; qualify the pointee or import it explicitly if a wildcard import does not establish its identity. Optional owners use the same scoped type-namespace proof described above; a wildcard import is accepted only when that proof is unique and complete.

Rooting keeps an owner alive; it does not serialize access to its Rust data or make that data Send or Sync. The caller must uphold the Rust type's thread requirements and prevent conflicting access by other Julia tasks, threads, callbacks or nested calls until the borrow ends. Rust must not retain the reference or use it asynchronously after returning. A mutable borrow changes the actual owner: an error, caught panic or callback exception can leave it partly changed; no rollback is promised.

Trait impls

#[julia] methods of a trait impl are bound too (#506). The wrapper calls the method through the trait (<Buf as tr::A>::m(..)), and the exported symbol carries the trait's name, length-prefixed, so it never clashes with an inherent method of the same name or with another trait's:

#[julia]
impl Buf {
    #[julia]
    pub fn m(&self) -> i32 { self.n }           // rustcall_Buf_m
}

#[julia]
impl tr::A for Buf {
    #[julia]
    fn m(&self) -> i32 { self.n * 10 }          // rustcall_Buf_1A_m
    #[julia]
    fn build(n: i32) -> Self { Buf { n } }      // rustcall_Buf_1A_build
}

#[julia]
impl B for Buf {
    #[julia]
    fn m(&mut self, by: i32) -> i32 { by }      // rustcall_Buf_1B_m
}

In Julia a trait method keeps its name unless another method of the struct has the same name. In that case the inherent method keeps the name, as it does in Rust's method resolution, and each trait's method is bound as <Trait>_<name>:

m(b)          # Buf::m
A_m(b)        # <Buf as tr::A>::m
B_m(b, 2)     # <Buf as B>::m
build(Buf, 1) # <Buf as tr::A>::build

The trait is named by the last segment of its path. A trait's function that returns Self is bound under its own name (build(Buf, 1)), not as another Buf(...) constructor that would shadow the inherent one. The crate scan refuses a crate in two cases rather than binding one method over another:

  • two traits whose paths end in the same name (a::Tr and b::Tr, or From<u8> and From<i32>) both wrap a method of one name, which would give them one symbol;
  • a qualified name is already taken (an inherent method literally named A_m).

A trait impl of a type declared without #[julia], or of a foreign or primitive type, is left alone. A trait impl through a type alias (impl Tr for Alias) fails the scan with the alias named: the wrappers carry the alias's name and the scan cannot tell which struct it names. Write the struct's own name instead.

Static methods

A method without self (other than a constructor) is called with the type as its first argument, the Julia spelling of Labeler::shout(s):

shout(Labeler, "hi")     # Labeler::shout
parse_scale(Divider, "7") # Divider::parse_scale

The bare shout("hi") form is generated as well, unless the crate also has a free #[julia] fn shout or another struct with a static shout: two bare definitions would overwrite each other — silently under @rust_crate, and as a hard error when a module written by write_bindings_to_file is precompiled — so in that case only the typed form exists and the free function keeps the bare name (#323).

Modules

Every exported symbol hangs off the item's FFI name: the item's own name at the crate root, and its module path folded in otherwise (rustcall_julia_core::codegen::symbol_stem, #300). A proc-macro cannot see the module an item sits in, so the module carries the marker too:

#[julia]
pub mod a {
    use rustcall_julia_macros::julia;

    #[julia]
    pub fn run() -> i32 { 1 }          // exported as `rustcall_a__run`

    #[julia]
    pub struct C { pub v: i32 }        // `a__C_free`, `a__C_get_v`, `a__C_set_v`

    #[julia]
    impl C {
        #[julia]
        pub fn new(v: i32) -> Self { Self { v } }   // `rustcall_a__C_new`
    }
}

#[julia]
pub mod b {
    use rustcall_julia_macros::julia;

    #[julia]
    pub fn run() -> i32 { 2 }          // exported as `rustcall_b__run`
}

#[julia]
pub fn run() -> i32 { 0 }              // crate root: `rustcall_run`, as before

#[julia] on an inline mod expands the #[julia] items inside it with the module path; nested marked modules accumulate (a::deep::run → rustcall_a__deep__run). Segments are joined with __ and every _ inside a segment is spelled _0, so a_b::c (a_0b__c) and a::b_c (a__b_0c) can never meet; a crate-root item keeps its bare name.

On the Julia side the generated module mirrors the Rust module tree — one submodule per Rust module, root items where they always were:

bindings = @rust_crate "/path/to/two_modules"
bindings.run()              # 0
bindings.a.run()            # 1
bindings.b.run()            # 2
c = bindings.a.C(Int32(4))  # a distinct type from bindings.b.C
bindings.a.get(c)

A module written by write_bindings_to_file has the same shape (module a ... end inside the generated module), and the static-method rule above is decided per module.

Three things to know:

  • A module's #[cfg] gates everything inside it: the manifest reports an item in #[cfg(feature = "x")] #[julia] pub mod a { ... } under feature = "x", so a build without the feature binds nothing from a.
  • Julia keeps functions, types and modules in one namespace where Rust keeps three, so a crate with both #[julia] fn a() and #[julia] mod a { ... } at the same level is refused when the bindings are laid out (the message names both sides); rename one of them.
  • A #[julia] item inside an inline module that is not marked #[julia] is refused by the scan, with the fix in the message: the proc-macro would have exported it under the crate-root symbol, which the manifest cannot describe honestly.
  • File modules (mod a;) cannot carry an attribute macro (rustc's E0658) and are transparent: their items keep crate-root symbols, exactly as if they were written in lib.rs. Two file modules that both define #[julia] pub fn run therefore still want one rustcall_run; the scan reports the duplicate with both locations instead of describing a library that cannot be built. Wrap the items in a #[julia] pub mod block inside the file, or rename one.

Names Julia reserves

Rust and Julia reserve different words. fn function, struct end, fn quote(&self) and a field begin are plain Rust, and a raw identifier (r#for, r#let, mod r#do) makes every Rust keyword available as a name. Julia reserves all of these, so each item is bound under a name Julia can parse (#514), decided in one place (RustCall.julia_binding_name) for every item kind — free function, method (inherent or a trait's), field, struct and module — in @rust_crate, in a file write_bindings_to_file writes, and in rust""":

  • a raw identifier loses its r# (r#match → match);
  • a name Julia reserves gets a trailing underscore (r#for → for_, end → end_, r#true → true_). The set is Julia's own: a name that Meta.parse does not read as a plain identifier by itself.
#[julia]
pub fn r#for(x: i32) -> i32 { x + 1 }          // rustcall_for

#[julia]
pub struct end { pub r#let: i32 }               // end_free, end_get_let

#[julia]
impl end {
    #[julia]
    pub fn new(v: i32) -> Self { end { r#let: v } }
    #[julia]
    pub fn quote(&self) -> i32 { self.r#let }   // rustcall_end_quote
}

#[julia]
pub mod r#do { /* #[julia] pub fn r#try ... */ }
bindings.for_(1)          # 2
e = bindings.end_(3)
bindings.quote_(e)        # 3
e.let_                    # 3; the accessors are get_let_ / set_let_!
bindings.do_.try_(4)

Arguments follow the same rule (#516). A generated wrapper's parameters are named by RustCall.julia_parameter_names, which every emitter reads — the parameter of #[julia] fn f(end: i32, r#for: &str) is f(end_, for_). A wrapper is called positionally, so only the written file and error messages show these names. Two parameters never share one: a renamed argument yields to an argument already called that (fn g(end: i32, end_: i32) is g(end__, end_)), and an argument with no Julia name of its own — a pattern such as (a, b): (i32, i32), or _ — is named after its position (arg1). A parameter never takes a name its wrapper uses itself (#526): the emitters name each parameter against every other name of the definition it lands in, so fn echo(pointer: &str) is echo(pointer_) where the wrapper calls pointer, and Int64: i64 is Int64_ where it converts through Int64.

The exported symbols do not change: they keep the Rust side's spelling without r#, as before. A trailing underscore can land on a name the crate already uses — fn r#for beside fn for_, a field r#let beside let_, a method r#end beside end_ on the same struct, struct r#while beside fn while_, mod r#do beside mod do_. The layout is then refused with both items named, rather than one binding silently replacing the other; rename one of them.

The check compares what the generated module actually defines (RustCall.julia_definitions): free functions, types and their constructors, static methods (typed, and bare unless a free function or another static method takes the name), instance methods, properties, the get_<f> / set_<f>! helpers and submodules. A module has one namespace, and a method of any struct is a method of the module's function of that name. Two rules follow:

  • Two definitions made by different items under one name and one dispatch key are refused. A method get_x beside a field x, whose accessor is also get_x(self), is refused this way. Instance methods of two structs overload one function and are fine.
  • A type's or submodule's name may be used by no function other than the type's own constructors and methods. A method of struct A bound as for_ beside struct for_ is refused.

The PyO3 host bindings run the same check over what they define. Static methods there are free functions, because the host passes no type, so #[staticmethod] fn for_ beside #[pyfunction] fn r#for is refused.

The check runs on the items of the build that is bound: the scan is made under the build's own configuration, so #[cfg(feature = "x")] fn r#for beside #[cfg(not(feature = "x"))] fn for_ is one item and is accepted.

Property Access Syntax

Generated struct wrappers support Julia's property access syntax for natural field access:

# Instead of calling accessor functions directly:
get_x(p)
set_x(p, 5.0)

# You can use dot notation:
p.x        # Get field value
p.x = 5.0  # Set field value

This works for all FFI-compatible field types (i8, i16, i32, i64, u8, u16, u32, u64, f32, f64, bool, usize, isize).

You can also use propertynames() to list available fields:

p = MyModule.Point(1.0, 2.0)
propertynames(p)  # => (:x, :y)

API Reference

scan_crate(path)

Scan a Rust crate and extract #[julia] marked items.

info = RustCall.scan_crate("/path/to/crate")

println("Crate: ", info.name)
println("Functions: ", length(info.julia_functions))
println("Structs: ", length(info.julia_structs))

generate_bindings(path; kwargs...)

Generate Julia bindings for an external crate.

bindings = RustCall.generate_bindings("/path/to/crate",
    output_module_name = "MyBindings",
    build_release = true,
    cache_enabled = true
)

eval(bindings)

# Now MyBindings module is available
MyBindings.add(1, 2)

@rust_crate

Scans, builds, generates and loads in one step, and returns the bindings.

# Basic usage
const MyCrate = @rust_crate "/path/to/crate"

# With options
const MyBindings = @rust_crate "/path/to/crate" name="CustomName" release=true cache=true

Every option is listed under Options of @rust_crate.

Type Definitions

CrateInfo

Information about a scanned Rust crate.

FieldTypeDescription
nameStringCrate name
pathStringAbsolute path
versionStringCrate version
dependenciesVector{DependencySpec}Dependencies
julia_functionsVector{RustFunctionSignature}#[julia] functions
julia_structsVector{RustStructInfo}#[julia] structs
source_filesVector{String}.rs file paths

CrateBindingOptions

Options for binding generation.

FieldTypeDefaultDescription
output_module_nameUnion{String, Nothing}nothingOverride module name
output_pathUnion{String, Nothing}nothingWrite generated code to file
use_wrapper_crateBooltrueCreate wrapper crate
build_releaseBooltrueBuild in release mode
cache_enabledBooltrueEnable library caching

Build Process

When you call @rust_crate, RustCall.jl:

  1. Scans the crate - Follows the module tree from src/lib.rs and records every #[julia] item (parsed by RustCall's Rust-side extractor, not by Julia)
  2. Checks cache - If a cached library exists with matching hash, uses it
  3. Builds the crate - If the crate already has cdylib crate-type, builds directly; otherwise creates a wrapper crate
  4. Generates Julia module - Creates wrapper functions and struct definitions
  5. Loads the library - Loads the compiled .so/.dylib/.dll

Caching

Compiled libraries are cached based on source code hash:

# Clear the cache
RustCall.clear_cargo_cache()

# Check cache size
RustCall.get_cargo_cache_size()

Supported Types

See What you get in Julia for the overview and The FFI Type Contract for the complete, generated table.

Precompilation Support

A package can carry a crate's bindings in two ways, and both precompile: use @rust_crate at the package's top level, or write the bindings to a file with write_bindings_to_file and include it.

Using @rust_crate inside a package

module MyPackage
using RustCall

# Build the crate and generate its bindings; define them as `MyPackage.Bindings`.
@rust_crate joinpath(@__DIR__, "..", "deps", "my_rust_crate") submodule="Bindings"
using .Bindings: add, multiply, MyStruct

export add, multiply, MyStruct
end

The generated module is evaluated inside the module that expands the macro (#339), so it is part of MyPackage and is compiled into MyPackage's precompile cache like any other submodule. What happens, and when:

  • When the package is precompiled (the first using, or Pkg.precompile()): @rust_crate scans the crate, builds it — the library goes into RustCall's cache under the depot's scratch space — and generates the module. Nothing is written into the package. The library is not opened at this point: Julia defers the generated module's __init__ to load time, so the bindings are callable after MyPackage.__init__, not from the package's own top level.
  • When the package is loaded from its cache: the generated module's __init__ opens the cached library (through a private per-process copy, so Cargo's output and the cache copy stay free to be rebuilt, #309). No scanning, no Cargo.
  • After an edit to the crate, or RustCall.clear_cache(): the module declared the library and the crate's own input files — the set the artifact identity is computed from, so a path dependency and a workspace root count too — with Base.include_dependency, so the package's precompile cache is stale and the next using re-precompiles the package, building the crate again. Deterministic, and never a failed dlopen of a path that is gone.

One thing Julia's invalidation cannot see: the environment. RUSTFLAGS, PYO3_PYTHON, a PYO3_CONFIG_FILE pointing at a different file — all of them decide the artifact, and none of them is a file the image can track. Change one and every tracked file is still what it was, so the image stays valid even though the library path names a build under the previous values. The generated module records the values it was built under and refuses to load at __init__ when they no longer match, naming the variables. For a @rust_crate module, re-run Pkg.precompile(; force = true) (or touch a source file of the crate) under the desired environment. A file written by write_bindings_to_file carries the record in its own source, so re-precompiling cannot help: write the file again with write_bindings_to_file under the desired environment (and RustCall), and a package that includes it re-precompiles on its own. The error names the remedy that fits the module (#531). The recorded toolchain includes RustCall's own extractor sources, so a RustCall release that changes them refuses files written by the previous one in the same way.

Those recorded values describe the build exactly. @rust_crate and write_bindings_to_file take one snapshot of the environment when they start. The cfg probe, the cache key, the registry name, every Cargo and Python subprocess and the recorded values all come from that snapshot, never from ENV read later. So another task that changes RUSTFLAGS or PATH during the build cannot produce a library built under one environment and recorded under another. When pyo3's build script configures the crate for a Python interpreter, that interpreter is asked again after the build. If it was replaced in place during the build, the build is refused before the library is cached or loaded.

cache=false is not the shape to use in a package. The library is then not the cache copy but whatever the build produced: Cargo's own output under RustCall's target directory for the crate (RustCall.crate_target_directory) for a crate that is already a cdylib, and a copy in a directory of its own under RustCall's Cargo cache — one the cache lookup never returns, and that only RustCall.clear_cache() removes — for a crate RustCall has to wrap. The copy outlives the process that made it on purpose: a package precompiled with cache=false is loaded by another process, which must still find the file. In the first case the next build of the crate by RustCall rewrites that file; in the second every precompilation leaves a copy behind until the cache is cleared.

The naming rule: submodule="Bindings" is what defines the module as MyPackage.Bindings, which is what using .Bindings: ... needs. Without it the module gets a hidden, per-call name (MyPackage.var"##RustCallCrateRuntime#N"...) and is reached only through the value the macro returns — nothing the caller did not name appears in its namespace. name="Bindings" chooses that hidden module's name and still defines nothing, which is why const MyBindings = @rust_crate path name="MyBindings" — the form the macro's docstring has always shown — keeps working: the constant is the only binding the caller gets.

A second @rust_crate ... submodule="Bindings" in the same module replaces the module (Julia warns replacing module Bindings); values obtained earlier keep the module they hold. Do not write const Bindings = @rust_crate path submodule="Bindings": that binds the returned value over the module the macro just defined. The return value is the same CrateBindings in every position — REPL, function body, package — so a package may also keep it: const B = @rust_crate path gives B.add(...), world-age-safe, without any visible module. The generated module needs only RustCall among the package's dependencies (it reaches Libdl through RustCall).

Prefer this shape when the machine that loads the package has a Rust toolchain and building the crate on first use is acceptable; the bindings can never be out of date with respect to the crate. Prefer the written file below when the package must load without Rust installed, or when the bindings and the library must be inspected, committed or shipped as files.

Generating Bindings to a File

using RustCall

# Generate bindings and write to a file
RustCall.write_bindings_to_file(
    "deps/my_rust_crate",              # Path to Rust crate
    "src/generated/MyRustBindings.jl", # Output file
    output_module_name = "MyRust",
    relative_lib_path = "../deps/lib"  # Path relative to the output file
)

Package Development Workflow

  1. Set up your package structure:

    MyPackage/
    ├── Project.toml
    ├── src/
    │   ├── MyPackage.jl
    │   └── generated/
    │       └── MyRustBindings.jl  # Generated bindings
    ├── deps/
    │   ├── my_rust_crate/         # Your Rust crate
    │   └── lib/                   # Compiled library
    └── test/
  2. Generate bindings during development:

    using RustCall
    RustCall.write_bindings_to_file(
        "deps/my_rust_crate",
        "src/generated/MyRustBindings.jl",
        output_module_name = "MyRust",
        relative_lib_path = "../deps/lib"
    )
  3. Include in your package:

    # In src/MyPackage.jl
    module MyPackage
    
    include("generated/MyRustBindings.jl")
    using .MyRust
    
    # Re-export functions if desired
    export add, multiply
    
    end
  4. The generated file uses @__DIR__ for library paths, ensuring it works when the package is installed elsewhere.

Like the in-memory module, the written file needs only RustCall among the package's dependencies: it reaches Libdl through RustCall (import RustCall.Libdl). Without relative_lib_path, the file names a copy of the library in RustCall's Cargo cache directory (removed by RustCall.clear_cache()), never a file inside the temporary wrapper project a crate without a cdylib target is built in.

Hot reload of a @rust_crate module

RustCall.enable_hot_reload_for_crate rebuilds a crate with its own cdylib target when its sources change, and swaps the new library in under the registry name the module loaded it as. Pass the value @rust_crate returned. Every generated module — in memory, or written by write_bindings_to_file — records everything its build was made from as one immutable RustCall.CrateBuildRecord, _BUILD_RECORD: the crate directory, the registry name (_LIB_NAME is read from it), the profile, features, default_features, the kind of build, the build environment (RUSTFLAGS and the rest of the allowlisted variables), the effective Cargo configuration and the toolchain. Every reload rebuilds from that record alone, so the rebuilt library has the #[cfg]s the module's wrappers were generated for:

B = @rust_crate "deps/my_rust_crate" release=false features=["simd"]
RustCall.enable_hot_reload_for_crate(B)  # rebuilds debug, with "simd"

Arguments are compared with the record, never added to it. The crate path may be omitted; when it is given it must name the recorded directory (a relative or symlinked spelling is fine), and lib_name, release, features and default_features, when given, must equal the recorded ones. The recorded environment is compared with the current one when hot reload is enabled and again before every rebuild. Any mismatch is refused: an ArgumentError at enable time, and a failed reload that keeps the previous library loaded (reported like any failed rebuild, through the callback) at rebuild time. Restore the environment, or load the crate again under the new one.

The path-only form, enable_hot_reload_for_crate(crate_path; release, features, default_features), constructs the same record from its keywords (defaulting to @rust_crate's defaults) and the current environment; it does not guess the build. Only a crate that is its own cdylib can be reloaded: both forms refuse a crate without one, or a module bound through a generated wrapper crate, when hot reload is enabled.

The rebuild is the build @rust_crate itself runs: RustToolChain's cargo, output under RustCall's own target directory for the crate (not the crate's target/), the library found under its [lib] name, and --offline under RUSTCALL_OFFLINE=1.

Hot Reload is the full guide: a runnable example, what a reload does to objects and call sites, the watcher's options and how to turn it off.

API Reference

write_bindings_to_file

RustCall.write_bindings_to_file(
    crate_path::String,
    output_path::String;
    output_module_name = nothing,
    build_release = true,
    relative_lib_path = nothing,
    strict = RustCall.FFI_STRICT[]
) -> String
ParameterTypeDescription
crate_pathStringPath to the Rust crate
output_pathStringPath for the generated Julia file
output_module_nameStringName for the generated module
build_releaseBoolBuild in release mode
relative_lib_pathStringPath for library relative to output file
strictSymbolWhat to do when the FFI type contract cannot describe a return type: :error (default), :warn, :none

Unsupported types in a crate

Every return type in the generated module is resolved through the FFI contract. A type the contract does not cover — a Vec<T> returned by value, say — used to be emitted as Any, which is not a well-defined ccall slot; it now raises, naming the signature:

the FFI contract cannot describe the return type of `mycrate::histogram(u32) -> Vec<f64>`

Change the Rust signature to something that can cross the boundary (return the aggregate behind a *mut, or expose accessors), or, to keep the rest of the crate building while you deal with it:

RustCall.write_bindings_to_file(crate_path, output_path; strict = :warn)

:warn restores the pre-#276 behaviour — one warning per signature and Any in the slot — for one minor release. The generated text also changed in two ways worth knowing about if you diff it against an older run: usize is spelled Csize_t, *mut i32 is Ptr{Int32} rather than Ptr{Cvoid}, and a String field is read as an owned buffer instead of Any.

emit_crate_module_code

RustCall.emit_crate_module_code(
    info::RustCall.CrateInfo,
    lib_path::String;
    module_name = nothing,
    use_relative_path = false
) -> String

Returns the generated Julia module code as a string.

Troubleshooting

The crate does not build

The Rust compiler's output is included in the error. Check first that the crate builds on its own (cargo build in the crate directory, if you have Rust installed), then that Cargo.toml lists rustcall_julia_macros under [dependencies] and that src/lib.rs has use rustcall_julia_macros::julia;. A message such as cannot find attribute julia in this scope means that use line is missing.

The first build needs network access to download dependencies. Offline, it fails while resolving them.

A function or method is missing from the bindings

  • The item needs #[julia]. For a method, both the impl block and the method need it.
  • The item may have been refused because of its signature. Run RustCall.boundary_report(crate_path): it names every refused item and the reason.
  • A generic function or struct cannot be bound from a crate; see Generic items are refused.
  • An item behind #[cfg(feature = "…")] exists only when that feature is enabled: pass features=[…].

A call raises InexactError or ArgumentError

Arguments are converted to the Rust type exactly. An integer that does not fit (2^40 for an i32) or a Vector{Int} passed where &[f64] is expected is refused in Julia before Rust is called. Convert on the Julia side.

The bindings do not reflect an edit

@rust_crate rebuilds when a source file changed, but a value obtained from an earlier @rust_crate keeps the module and library it was created with. Call @rust_crate again and use the new value, or use Hot Reload.

Precompilation issues

If you encounter precompilation issues:

  • Ensure the library path is correct (use relative_lib_path for portable packages)
  • Check that the library was copied to the correct location
  • Verify the generated code compiles without errors
  • With @rust_crate at a package's top level: the package must depend on RustCall, the crate must build on the machine that precompiles the package, and calls into the bindings belong after the package's __init__ (the library is not open while the package's top level runs during precompilation). Base.isprecompiled(Base.identify_package("MyPackage")) says whether the cache is currently valid; it turns false after RustCall.clear_cache() until the next using rebuilds.

Object lifetime

A struct handed to Julia by a @rust_crate binding is owned by Julia: its finalizer calls the Rust destructor, so the Rust allocation is released when the wrapper is collected. This is now also true of inline rust""" structs, which used to leak.

The finalizer captures what it needs at construction — the destructor pointer and a flag saying whether the library is still loaded — so it takes no lock and resolves no symbol when it runs. Two consequences worth knowing:

  • A method call or field access on an object whose finalizer has already run raises RustCall.RustError. Inline instance methods validate the receiver before preparing other arguments, resolving a Rust call target or entering native code, regardless of return shape. A finalized receiver is never interpreted as a static call; valid static methods and constructors remain callable without an instance.
  • Unloading a library retires the objects it produced: their finalizers become no-ops instead of calling into an image that is no longer mapped. That leaks those objects deliberately — a leak is preferable to a jump into freed text.

If you need a Rust object to outlive its Julia wrapper, keep a reference to the wrapper, or hold it inside GC.@preserve for the region where the raw pointer is used. Explicit raw-pointer arguments remain unchecked: callers must ensure pointer validity, lifetime and compatible aliasing; receiver validation does not validate those pointers. An allocation made by one library must be released by that same library; see Panics, Visibility and Lifetime for the full contract.

Regenerating bindings after an upgrade

Files written by write_bindings_to_file carry a format marker (# Bindings format: 0.10). Since #489 the format is the MAJOR.MINOR of the RustCall release that wrote the file — RustCall.BINDINGS_FORMAT_VERSION, read from Project.toml — and the file checks it when it is loaded (const _BINDINGS_FORMAT = RustCall.check_bindings_format("0.10"), and again in its __init__):

  • Same MAJOR.MINOR, any patch: the file loads. A patch release never changes the bindings format, so a file written by one release of a minor series loads under every later patch release of it.
  • Different minor or major: the file is refused with an error telling you to regenerate it with RustCall.write_bindings_to_file(crate_dir, output_path). The header of every generated file names the crate it was written from.
  • Integer markers (13 and below): files written by RustCall v0.6.6 and earlier used an integer format of their own. They are no longer readable and are refused with the same message; regenerate them.

The integer formats, and what each one introduced, are listed below for reference.

Format 13 (#474) records every input of the file's build — the crate directory, the registry name, the profile and features, the kind of build, the build environment, the Cargo configuration and the toolchain — as one RustCall.CrateBuildRecord named _BUILD_RECORD, the same record an in-memory @rust_crate module holds. It is what RustCall.enable_hot_reload_for_crate rebuilds from (see Hot reload). Its __init__ also checks the recorded build environment before loading, exactly as an in-memory @rust_crate module does: a written (or precompiled) module refuses to load under another RUSTFLAGS, PYO3_PYTHON, Cargo configuration or toolchain. A file emitted at this version does not load against a RustCall that predates the name; a file emitted before it records no build, and its module is refused by the module form of hot reload.

Format 12 (#460) hands Rust each callback argument as @cfunction(RustCall.CallbackSlot{k, R}(), ...), a slot that knows its return type: invoked with no call in progress it records an error and returns a zero of R instead of raising through Rust. Owned-buffer returns are guarded with a four-argument _guard_panic(value, channel, name, free_ptr), so a String a call returned is released, not leaked, when a callback's exception is raised. Both names are new, so a file emitted at this version does not load against an older RustCall.

Format 11 (#253) gives every call site in the file a RustCall.CrateTargetCache of its own, declared as a const beside the wrapper that uses it, and passes it to the target helpers. A wrapper then reuses the snapshot it last resolved instead of taking REGISTRY_LOCK and looking two symbols up on every call — about 1.0 µs and 14 allocations down to 22 ns and none, and calls from several threads no longer queue behind one another. A file emitted at this version does not load against a RustCall that predates the name.

Format 7 (#300) names every symbol module-qualified (a__C_free, rustcall_a__run) and puts items inside Rust modules into Julia submodules. A file emitted before it names symbols that a library built with the current proc-macro no longer exports for any item inside a module.

Since format 6 (#309) the module's __init__ opens a private generation copy of the library rather than the file _LIB_PATH names, exactly as @rust_crate does: that file is Cargo's output (or the copy write_bindings_to_file made of it), and an image mapped in place cannot be overwritten on Windows — the next cargo build of the crate, and the next regeneration of the file, would fail with "Access is denied".

Version 3 is the first that does not keep working when it is older than the RustCall loading it: the emitted wrappers name RustCall.ffi_string_argument, and 4 adds RustCall.FFIByValue, neither of which earlier versions have. A file at version 2 or below still loads — it uses only API that still exists — but does not get the unload, panic-containment, lifetime, UTF-8 or by-value guarantees described above.

Borrowing numeric slices

A non-generic #[julia] signature opts into checked, non-copying lowering of primitive &[T] and &mut [T] arguments. For example:

#[julia]
pub fn transform(input: &[f64], output: &mut [f64]) -> Result<(), String> {
    if input.len() != output.len() {
        return Err("length mismatch".into());
    }
    for (x, y) in input.iter().zip(output) {
        *y = x * 2.0;
    }
    Ok(())
}
input = [1.0, 2.0, 3.0]
output = zeros(3)
bindings.transform(input, output)  # output now contains [2.0, 4.0, 6.0]

Use the generated Julia function (transform(input, output)) for this checked lowering, including the functions emitted by @rust_crate and write_bindings_to_file. Raw @rust/ccall access to the exported C symbol is the manual ABI interface: it does not synthesize these slice checks or length slots, and its caller must uphold the complete pointer/length contract.

The manifest records each argument's abi (slice or slice_mut), slice_element representation, and slice_length = "usize". Julia validates these fields and the actual array element type; it does not infer a Rust layout from a raw pointer. The generated C shim receives a primitive pointer and a usize length (size_t), then reconstructs the Rust slice inside its panic boundary. Rust's native fat-pointer ABI never crosses the boundary. Every slice-bearing wrapper exports a <symbol>_slice_ptr_len_v1 producer marker. Bindings verify its presence on the captured library image before entering Rust, including constructors and every return shape. A crate built with an older rustcall_julia_macros is refused: update that dependency to 0.7.0 or later, rebuild, and regenerate bindings. Slice-free functions do not require the new marker.

The supported layouts are finite:

Rust elementJulia element
f32, f64Float32, Float64
i8, i16, i32, i64Int8, Int16, Int32, Int64
u8, u16, u32, u64UInt8, UInt16, UInt32, UInt64
isize, usizeInt, UInt
num_complex::Complex<f32>, num_complex::Complex32ComplexF32
num_complex::Complex<f64>, num_complex::Complex64ComplexF64

Complex values use the num_complex C layout, real component followed by imaginary component. Use the fully qualified Rust complex spelling shown in the table. User aliases, bool, char, nested slices, arbitrary structs and other element layouts are unsupported. There is no dtype conversion.

Built-in StridedVector{T} storage with stride one is borrowed directly: a dense vector, a contiguous vector view (including a matrix column), or a compatible reinterpret vector. Multidimensional arrays, arbitrary custom AbstractVector implementations, reversed views and non-unit-stride views are rejected; this mode never silently stages a copy. Before entering Rust, Julia checks the element representation, length multiplication, address span and alignment, and roots the array and its owner through the call. All elements must already be initialized, including mutable output storage: use zeros(T, n) or initialize every element before borrowing. Vector{T}(undef, n) is not a write-only slice contract. Empty slices use a non-null aligned dangling pointer; no element is read. The Rust shim checks its pointer/length arithmetic before constructing a reference.

All supplied slice ranges are checked together. Shared/shared overlap is allowed. A mutable slice overlapping another live buffer borrow is rejected, including identical arrays, partial overlap and overlapping reinterpret views. These checks cover the arguments of this call, not arbitrary references held elsewhere. Rust also checks the complete inline extent of borrowed receiver/handle objects before constructing slice references, including every present optional owner. An absent optional owner contributes no object span. An opaque object's separately allocated interior buffers are not discoverable from its object address; the caller must exclude hidden aliases, including aliases created with unsafe_wrap. Raw pointers remain an explicit unchecked interface for required owner/raw-pointer positions. Generated optional-owner argument positions reject them, including C_NULL. Neither allocation provenance nor the validity of manually constructed unsafe array owners can be established from their addresses.

The scope ends at the synchronous return from Rust. Static or otherwise retaining lifetimes, borrowed returns from a lowered slice, and generic slice signatures are refused. Rust must not retain these pointers, launch background work that uses them, or use them after returning. GC rooting keeps storage alive; it does not lock that storage. The caller must prevent another Julia task, OS thread or callback (including reentrant RustCall calls) from accessing a mutable borrow, and prevent mutation, resizing or freeing of a shared borrow until the call finishes.

Mutable borrows write the caller's storage directly. A returned Err, a caught Rust panic or a Julia callback exception can leave it partly changed; there is no rollback or success-only copy-back. Use RustCall.with_numeric_buffer(...; write=true) when explicit staging is wanted, and throw on an error result before its callback returns normally to skip copy-back. Owned Vec returns and multidimensional stride descriptors are separate interfaces.

Scoped numeric buffers

RustCall.with_numeric_buffer is a copying helper for existing #[julia] methods with a primitive pointer and length. The helper itself does not lower Rust slices or return a Rust-owned Vec; signature-aware slice borrowing is described above. For a Rust method sum(*const f64, usize), for example:

value = RustCall.with_numeric_buffer(array; element_type=Float64) do ptr, len
    bindings.sum(ptr, len)
end

The helper passes an aligned, contiguous temporary in eachindex order, even for non-contiguous views. It keeps that buffer alive for the callback and passes a non-null aligned pointer for an empty array. The pointer must never be retained, used asynchronously, or accessed after the callback. The caller must ensure the Julia element layout is compatible with the Rust pointer type; the helper accepts only Bool, 8/16/32/64-bit signed and unsigned integers, Float32, Float64, ComplexF32, and ComplexF64, and element_type checks the caller-declared Julia element type against the array. The raw pointer cannot reveal the callback's Rust type, so the caller must ensure the actual Rust representation matches; no dtype conversion is performed.

For a mutable output pointer, pass write=true. The temporary is copied back only after the callback returns normally; throw in the callback when the Rust method returns an error status if copy-back should be skipped. A successful return value representing an error is still a normal return. The caller must ensure Rust writes valid Julia values and must prevent concurrent access to the source array. Copy-back itself can fail if the array is immutable or implements throwing setindex!, and such a failure may leave it partly updated. Rust-owned bulk outputs still need explicit ownership and release handling.

When an API transfers a Rust allocation as a pointer and length and provides its matching release function, RustCall.copy_owned_numeric_buffer copies the values and invokes that release callback in finally, including when Julia validation fails:

values = RustCall.copy_owned_numeric_buffer(ptr, len) do p, n
    bindings.free_values(p, n)  # the allocator's own release function
end

The pointer must be live, point to len initialized elements with a compatible layout, and belong to that release function. Neither provenance nor allocation length can be checked. The release callback is also responsible for handling an invalid length if the caller supplies one. No other task may read, mutate, or free the allocation while copying. A null pointer is accepted only for zero length; empty allocations are still passed to the release callback. This helper does not understand a Rust Vec's ownership or capacity on its own.

Explicit instances of generic types

#[julia] crate items themselves cannot be generic. If a dependency exposes a public generic struct, RustCall.generate_crate_instances can generate a Rust facade source file for explicitly declared concrete instances and methods:

instances = [(
    name = "FloatCell",
    rust_type = "generic_crate::Cell<f32>",
    constructor = (name = "new", args = ["value" => "f32"]),
    methods = [
        (name = "get", args = Pair{String,String}[], return_type = "f32", mutable = false),
        (name = "set", args = ["value" => "f32"], return_type = "()", mutable = true),
    ],
)]
write("facade/src/lib.rs", RustCall.generate_crate_instances(instances))
# Supply a Cargo.toml for the facade with dependencies on generic_crate and
# rustcall_julia_macros, then load that facade with @rust_crate.

Argument pairs can also explicitly borrow another declared wrapper:

(name = "combine", args = ["other" => (wrapper = :FloatCell, mutable = false)],
 return_wrapper = :FloatCell, mutable = false)

The generated argument is other: &FloatCell, and default forwarding passes &other.inner to the native method. Set the mapping's mutable = true for &mut FloatCell and &mut other.inner. Mapping mutability defaults to false; method mutable still controls self. Constructors accept the same mapped arguments and forward their .inner references to the native constructor. Such constructors emit the explicit owned-return proof and producer marker for their own wrapper. A one-argument mapped constructor requires its declared owner argument; raw Ptr/C_NULL shorthand cannot bypass those checks. Legacy constructors retain their existing source and ABI.

Checked handles retain their normal type, liveness, library-image, GC-rooting and alias checks. Repeated shared borrows are allowed; a mutable receiver or argument may not alias another borrow of the same owner.

return_wrapper names the owner of the native result, including the current wrapper or a different wrapper declared later in the specification. Add error_type = "String" for a Result<Wrapper, String> result. For example, these methods can live on a matrix-like owner whose native methods produce a factor:

(name = "factor", args = Pair{String,String}[],
 return_wrapper = :Factor, mutable = false)
(name = "checked_factor", args = ["other" => (wrapper = :FloatCell,)],
 return_wrapper = :Factor, error_type = "String", mutable = false,
 expression = "self.inner.checked_factor(&other.inner)")

A trusted method expression is emitted verbatim in wrapper-variable scope: self is the current wrapper and mapped arguments are wrapper references. Explicit expressions access .inner themselves and produce the native inner value, or its Result; default forwarding accesses .inner automatically. Julia neither parses nor substitutes Rust expressions.

The generator first inventories every wrapper name, so forward mappings work. Duplicate names/parameters/methods, unknown wrappers or fields, non-Boolean mutability, and conflicting return_type/return_wrapper/error_type combinations fail before source is returned. Legacy constructor and simple method declarations keep their source form. Cargo/rustc validates concrete native signatures, bounds and trusted expressions.

Explicit owned mappings emit #[rustcall_owned_return(Wrapper)] immediately after #[julia]. The shared Rust generator proves the actual returned value is a sized, 'static annotated owner. For this proof, references reconstructed from raw receiver, slice or present optional-owner pointers are tied to a call-local witness: they cannot be inferred as 'static merely because they arrived through a C pointer. nothing reconstructs no borrowed owner. The owner marker trait itself imposes no blanket 'static bound; the explicit return check applies to the actual produced value, preserving existing lifetime-bearing owner behavior elsewhere.

The manifest records the selected owner, and bindings require the producer's <symbol>_owned_return_v1 ABI marker. Slice and optional-owner producer markers used by the same signature remain required independently. Legacy boxed Result<Self, E> marker checks remain in place. Successful values capture the selected owner's destructor, panic channel and liveness from the library image that produced them, independently of the receiver's owner. The selected owner is freed if Julia adoption fails. Rust normally drops temporaries on Err or a caught panic; returning a different owner does not transfer it to a replacement image after hot reload.

The generated structs own the concrete Rust values and RustCall's normal struct finalizers drop them. Generated methods supply no application locks, synchronization or numerical policies; callers must prevent concurrent access that violates Rust aliasing rules or the concrete type's thread-safety requirements. The source is deterministic for a given ordered specification; because it is written to the facade crate before loading, normal Cargo and RustCall build invalidation applies. Type expressions and method signatures are trusted Rust source: the caller chooses them, and cargo checks them. The generator does not inspect dependencies or infer methods, bounds, return conversions or lifetimes. Result and argument mappings are explicit; no private upstream layout is inspected. A fallible constructor can specify error_type = "String" (or another supported error type); the resulting constructor returns a RustResult whose success value owns the wrapper. An optional trusted Rust expression supplies the underlying constructor call, for example to assemble a Vec from an input pointer and length and convert an error to String. The caller must ensure any such pointer is valid and preserve the source through the call; use the scoped buffer helper where appropriate. Unsupported ABI types, borrowed results and trait methods needing extra imports require a hand-written facade. It does not generate a Cargo.toml.

RustCall.with_numeric_buffer — Function
RustCall.with_numeric_buffer(f, array; write=false, element_type=eltype(array))

Call f(pointer, length) with a scoped, contiguous copy of a Julia numeric array. The pointer is valid only until f returns and must not be retained. f must use it synchronously and must use a Rust element type with the same representation as Julia's eltype(array). No conversion of element type or byte order is performed.

When write=true, values are copied back to array only after f returns normally; if f throws, the original array is unchanged. The caller must prevent concurrent access to array during the call and ensure any values written by foreign code are valid Julia values of the element type. A returned error status is a normal return: throw in f to prevent copy-back. Empty arrays are passed with length zero and a valid aligned non-null pointer.

This helper supports Bool, 8/16/32/64-bit signed and unsigned integers, Float32, Float64, ComplexF32 and ComplexF64. The element_type keyword checks the declared Julia element type against the array. The caller must still ensure the callback uses the matching Rust representation; a raw pointer cannot carry or validate a Rust type. The helper does not keep pointers returned or captured by f alive after the call. It copies views in eachindex order; arbitrary user-defined array indexing and copy-back methods may throw. It is not an owned Rust Vec conversion.

source
RustCall.copy_owned_numeric_buffer — Function
RustCall.copy_owned_numeric_buffer(release, pointer::Ptr{T}, length)

Copy length elements from a Rust-owned contiguous buffer into a Julia Vector{T} and call release(pointer, length) exactly once in a finally block, including if validation or copying fails. release must invoke the destructor supplied by the same Rust library that allocated the buffer. This is an unsafe FFI boundary: the caller must supply a live, aligned pointer valid for reads of length initialized T values, with compatible Rust/Julia layout, and must ensure no other thread accesses or releases it. A nonempty buffer may not have a null pointer. Pointer provenance and allocation length cannot be verified by this function. Zero-length buffers are not dereferenced.

Use only with an API whose ownership has actually been transferred to Julia; never release borrowed pointers or assume a Rust Vec layout.

source
RustCall.generate_crate_instances — Function
RustCall.generate_crate_instances(instances) -> String

Generate Rust source for a finite set of concrete owned #[julia] wrapper structs around generic types. Each entry is a named tuple with fields name, rust_type, constructor, and methods. A constructor has name and args (a vector of name => rust_type pairs). A fallible constructor additionally has error_type (a Rust type supported by RustCall's Result ABI). An optional expression supplies a trusted Rust expression in the declared arguments; it must produce the concrete type or, for fallible constructors, its Result. A method has name, args, mutable (Bool), and either a legacy return_type or an explicit return_wrapper naming a declared wrapper. An argument value (wrapper = :Other, mutable = false) emits &Other and forwards &arg.inner; mutable = true emits and forwards mutable references. Wrapper mappings can refer to declarations later in the specification. Constructors can use the same mapped arguments; these constructors opt into explicit owned-return proofs and ABI markers. A one-argument mapped constructor requires its declared owner and rejects raw pointer-adoption shorthand. return_wrapper wraps the native result into that owner; adding error_type wraps the success of a Result. It conflicts with return_type. A trusted method expression is emitted verbatim in wrapper-variable scope: self is the current wrapper and mapped arguments are wrapper references, so an explicit expression accesses their .inner fields itself. It must produce the native inner value (or its Result), not a generated wrapper. The generated constructor calls the specified associated function on the concrete type and wraps the returned value; methods forward to &self or &mut self. These Rust functions and types must be public and their concrete signatures must match the declarations.

The output is Rust source to place in a facade crate that depends on both the original crate and rustcall_julia_macros, then load with @rust_crate. rust_type, argument types and return types are trusted Rust source, checked by cargo rather than parsed or sanitized by this function. RustCall's normal crate binding rules determine which concrete signatures can cross the ABI. The wrapper owns its value; normal RustCall struct finalization drops it. The generator adds no synchronization: callers must prevent concurrent access that violates Rust's aliasing or the underlying type's thread-safety rules. This API does not infer methods, trait bounds, associated types, conversions, or lifetimes. Write custom wrappers for those cases.

source