Types, memory and ownership

The Julia-side wrapper types (RustResult, RustOption, RustBox, RustRc, RustArc, RustVec, RustSlice, RustPtr, RustRef, RustString, RustStr) and their operations, the ownership operations backed by the Rust helpers library (deps/rustcall_helpers/), and the Julia types generated for #[julia] structs. See Struct Mapping for the user-facing guide.

Wrapper types (src/ffi/types.jl)

Base.Vector — Method
Vector(vec::RustVec{T}) -> Vector{T}

Convert a RustVec to a Julia Vector by copying the data.

Example

vec = RustVec{Int32}(ptr, 10, 20)
julia_vec = Vector(vec)  # Creates a new Julia array

Note

This creates a copy of the data. Modifications to the returned Vector will not affect the original RustVec.

source
RustCall.RustArc — Type
RustArc{T}

Represents Rust's Arc<T> type - an atomically reference-counted pointer (thread-safe). Multiple RustArc instances can share ownership across threads.

Memory Management

  • Atomic reference counting is managed by Rust
  • Safe to share across Julia tasks/threads
  • Call drop! to decrement reference count

Example

# Create an Arc (from Rust)
arc = RustArc{MyData}(ptr)

# Clone for another owner
arc2 = clone(arc)

# Safe to use in different tasks
@spawn begin
    # Use arc2
end
source
RustCall.RustBox — Type
RustBox{T}

Represents Rust's Box<T> type - a heap-allocated value with single ownership. The memory is owned by this wrapper and should be dropped when no longer needed.

Memory Management

  • RustBox owns its data and is responsible for calling drop
  • Use drop! to explicitly release the memory
  • Finalizers can be attached for automatic cleanup

Example

# Create a Box (typically from Rust)
box = RustBox{Int32}(ptr)

# Access the value
value = deref(box)

# Drop when done
drop!(box)
source
RustCall.RustOption — Type
RustOption{T}

Represents Rust's Option<T> type on the Julia side.

FFI Compatibility Note

This type uses a Julia Union{T, Nothing} field which does NOT match C struct layout. It is intended for Julia-side representation only. For actual FFI with Rust, use CRustOption which has a C-compatible layout with UInt8 discriminant and Ptr{Cvoid} value pointer. Conversion between CRustOption and RustOption should be done explicitly in the binding layer.

source
RustCall.RustPtr — Type
RustPtr{T}

A pointer to a Rust value of type T. Corresponds to *const T or *mut T in Rust.

source
RustCall.RustRc — Type
RustRc{T}

Represents Rust's Rc<T> type - a reference-counted pointer (single-threaded). Multiple RustRc instances can share ownership of the same data.

Memory Management

  • Reference counting is managed by Rust
  • Julia side should call clone to create new references
  • Call drop! to decrement reference count

Note

Rc<T> is not thread-safe. For multi-threaded scenarios, use RustArc{T}.

source
RustCall.RustRef — Type
RustRef{T}

A reference to a Rust value of type T. Corresponds to &T or &mut T in Rust. Note: In C ABI, references are passed as pointers.

source
RustCall.RustResult — Type
RustResult{T, E}

Represents Rust's Result<T, E> type on the Julia side.

FFI Compatibility Note

This type uses a Julia Union{T, E} field which does NOT match C struct layout. It is intended for Julia-side representation only. For actual FFI with Rust, use CRustResult which has a C-compatible layout with UInt8 discriminant and Ptr{Cvoid} value pointer. Conversion between CRustResult and RustResult should be done explicitly in the binding layer.

source
RustCall.RustSlice — Type
RustSlice{T}

Represents Rust's slice type &[T] - a borrowed view into a contiguous sequence.

Fields

  • ptr: Pointer to the first element
  • len: Number of elements

Note

This is a borrowed reference; the underlying data must outlive the slice.

source
RustCall.RustStr — Type
RustStr

Represents Rust's string slice &str. This is a borrowed reference, so the memory is managed elsewhere.

source
RustCall.RustString — Type
RustString

Represents Rust's owned String type. This is a wrapper around a pointer to a Rust String. The memory is managed by Rust (via Box or similar).

Memory Management

When a Rust function returns a String, it should be freed using drop_rust_string or similar function provided by the Rust side.

source
RustCall.RustVec — Type
RustVec{T}

Represents Rust's Vec<T> type - a growable array.

Fields

  • ptr: Pointer to the data
  • len: Number of elements
  • cap: Capacity (number of elements that can be stored without reallocation)

Memory Management

  • The vector owns its data
  • Use drop! to release memory when done

Example

# Create from Rust
vec = RustVec{Int32}(ptr, len, cap)

# Access length
length(vec)  # => len

# Convert to Julia array (copies data)
julia_arr = collect(vec)
source
RustCall.RustVec — Method
RustVec(v::Vector{T}) -> RustVec{T}

Create a RustVec from a Julia Vector by copying the data to Rust memory.

Arguments

  • v: A Julia Vector to convert

Example

julia_vec = [1, 2, 3, 4, 5]
rust_vec = RustVec(julia_vec)  # Creates a RustVec{Int64}

Note

This function requires the Rust helpers library to be built. The data is copied to Rust-managed memory.

source
Base.collect — Method
collect(vec::RustVec{T}) -> Vector{T}

Alias for Vector(vec::RustVec{T}). Convert a RustVec to a Julia Vector.

Example

vec = RustVec{Int32}(ptr, 10, 20)
julia_vec = collect(vec)  # Creates a new Julia array
source
Base.getindex — Method
getindex(slice::RustSlice{T}, i::Int) -> T

Get the element at index i in a RustSlice.

Arguments

  • slice: The RustSlice to index into
  • i: The index (1-based, like Julia arrays)

Example

slice = RustSlice{Int32}(ptr, 10)
value = slice[1]  # Get first element

Note

This performs bounds checking. The index must be between 1 and length(slice).

source
Base.getindex — Method
getindex(vec::RustVec{T}, i::Int) -> T

Get the element at index i in a RustVec.

Arguments

  • vec: The RustVec to index into
  • i: The index (1-based, like Julia arrays)

Example

vec = RustVec{Int32}(ptr, 10, 20)
value = vec[1]  # Get first element

Note

This performs bounds checking. The index must be between 1 and length(vec).

source
Base.iterate — Method
iterate(slice::RustSlice{T}, state=1) -> Union{Tuple{T, Int}, Nothing}

Iterate over elements in a RustSlice.

Example

slice = RustSlice{Int32}(ptr, 10)
for x in slice
    println(x)
end
source
Base.iterate — Method
iterate(vec::RustVec{T}, state=1) -> Union{Tuple{T, Int}, Nothing}

Iterate over elements in a RustVec.

Example

vec = RustVec{Int32}(ptr, 10, 20)
for x in vec
    println(x)
end
source
Base.setindex! — Method
setindex!(vec::RustVec{T}, value, i::Int) -> value

Set the element at index i in a RustVec to value.

Arguments

  • vec: The RustVec to modify
  • value: The value to set (must be convertible to type T)
  • i: The index (1-based, like Julia arrays)

Example

vec = RustVec{Int32}(ptr, 10, 20)
vec[1] = 42  # Set first element to 42

Note

This performs bounds checking. The index must be between 1 and length(vec).

source
RustCall.drop! — Method
drop!(x::Union{RustBox, RustRc, RustArc, RustVec})

Drop an ownership type, calling the appropriate Rust-side drop function if the Rust helpers library is loaded. This is a fallback definition that will be overridden by the type-specific drop! methods in memory.jl once it is loaded. The fallback only marks the object as dropped without freeing Rust memory.

source
RustCall.is_dropped — Method
is_dropped(x::Union{RustBox, RustRc, RustArc, RustVec}) -> Bool

Check if an ownership type has been dropped.

source
RustCall.is_valid — Method
is_valid(box::RustBox) -> Bool

Check if a RustBox is still valid (not dropped and not null).

source
RustCall.julia_string_to_cstring — Method
julia_string_to_cstring(s::String) -> String

Prepare a Julia String for FFI (to be converted to Cstring by ccall). Note: The actual conversion happens at ccall time via cconvert/unsafe_convert.

source
RustCall.julia_string_to_rust — Method
julia_string_to_rust(s::String) -> RustStr

Convert a Julia String to a RustStr (borrowed reference). Note: The returned RustStr is only valid while the Julia String exists. For FFI, you typically want to use Cstring instead.

source
RustCall.rust_string_to_julia — Method
rust_string_to_julia(rs::RustString) -> String

Convert a RustString to a Julia String. This copies the data from Rust memory to Julia memory.

source
RustCall.snake_to_pascal — Method
snake_to_pascal(s::AbstractString) -> String

Convert a snakecase or kebab-case string to PascalCase (CamelCase). Handles both underscore (`) and hyphen (-`) as separators.

Examples

julia> snake_to_pascal("sample_crate")
"SampleCrate"

julia> snake_to_pascal("my_rust_lib")
"MyRustLib"

julia> snake_to_pascal("sample-rs")
"SampleRs"

julia> snake_to_pascal("my-rust-lib")
"MyRustLib"
source
RustCall.unwrap — Method
unwrap(option::RustOption)

Unwrap a RustOption, returning the Some value or throwing an error.

source
RustCall.unwrap — Method
unwrap(result::RustResult)

Unwrap a RustResult, returning the Ok value or throwing an error.

source
RustCall.unwrap_or — Method
unwrap_or(result::RustResult{T, E}, default::T)

Unwrap a RustResult, returning the Ok value or the provided default.

source
RustCall.unwrap_or — Method
unwrap_or(option::RustOption{T}, default::T)

Unwrap a RustOption, returning the Some value or the provided default.

source

Memory and ownership (src/ffi/memory.jl)

Base.push! — Method
push!(vec::RustVec{T}, value::T) -> RustVec{T}

Push a value to RustVec. Note: This modifies the vec in place by updating its internal pointer, length, and capacity.

source
RustCall._defer_drop — Method
_defer_drop(ptr::Ptr{Cvoid}, type_name::String, drop_symbol::Symbol)

Record a pointer for deferred deallocation when the Rust helpers library becomes available. If the queue exceeds MAX_DEFERRED_DROPS, attempts a flush first.

source
RustCall._defer_vec_drop — Method
_defer_vec_drop(ptr::Ptr{Cvoid}, len::UInt, cap::UInt, type_name::String, drop_symbol::Symbol)

Record a RustVec pointer for deferred deallocation (needs len/cap for CRustVec reconstruction). If the queue exceeds MAX_DEFERRED_DROPS, attempts a flush first.

source
RustCall.clone — Method
clone(arc::RustArc{T}) -> RustArc{T} where T

Clone a RustArc, incrementing the atomic reference count.

source
RustCall.clone — Method
clone(rc::RustRc{T}) -> RustRc{T} where T

Clone a RustRc, incrementing the reference count.

source
RustCall.copy_to_julia! — Method
copy_to_julia!(vec::RustVec{T}, dest::Vector{T}) -> Int

Copy RustVec contents to a pre-allocated Julia Vector using efficient Rust FFI.

This is the most efficient way to transfer data from Rust to Julia when you already have a destination buffer allocated.

Arguments

  • vec::RustVec{T}: Source RustVec to copy from
  • dest::Vector{T}: Pre-allocated destination Julia Vector

Returns

  • Int: Number of elements actually copied (min of source and dest lengths)

Throws

  • ErrorException: If the vec has been dropped
  • ErrorException: If the Rust helpers library is not loaded

Example

rust_vec = create_rust_vec(Int32[1, 2, 3, 4, 5])

# Copy all elements
dest = Vector{Int32}(undef, 5)
n = copy_to_julia!(rust_vec, dest)
@assert n == 5 && dest == Int32[1, 2, 3, 4, 5]

# Copy to smaller buffer (partial copy)
small_dest = Vector{Int32}(undef, 3)
n = copy_to_julia!(rust_vec, small_dest)
@assert n == 3 && small_dest == Int32[1, 2, 3]

drop!(rust_vec)

Performance

This function uses a single FFI call to copy all data, making it much more efficient than element-by-element access for large vectors.

See also: to_julia_vector, create_rust_vec

source
RustCall.create_rust_arc — Method
create_rust_arc(value::T) -> RustArc{T} where T

Create a RustArc from a Julia value. Automatically calls the appropriate Rust Arc::new function.

source
RustCall.create_rust_box — Method
create_rust_box(value::T) -> RustBox{T} where T

Create a RustBox from a Julia value. Automatically calls the appropriate Rust Box::new function.

source
RustCall.create_rust_rc — Method
create_rust_rc(value::T) -> RustRc{T} where T

Create a RustRc from a Julia value. Automatically calls the appropriate Rust Rc::new function.

source
RustCall.create_rust_vec — Method
create_rust_vec(v::Vector{T}) -> RustVec{T}

Create a RustVec from a Julia Vector by copying data to Rust-managed memory.

Arguments

  • v::Vector{T}: A Julia Vector to convert. Supported types: Int32, Int64, Float32, Float64

Returns

  • RustVec{T}: A new RustVec containing a copy of the data

Throws

  • ErrorException: If the Rust helpers library is not loaded
  • ErrorException: If the element type is not supported

Example

julia_vec = Int32[1, 2, 3, 4, 5]
rust_vec = create_rust_vec(julia_vec)
@assert length(rust_vec) == 5
drop!(rust_vec)  # Clean up when done

Note

The data is copied to Rust-managed memory. The original Julia array is not modified. Remember to call drop!(rust_vec) when done to free Rust memory.

See also: to_julia_vector, drop!

source
RustCall.drop_rust_arc — Method
drop_rust_arc(arc::RustArc{T}) where T

Drop a RustArc, decrementing the atomic reference count. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.

source
RustCall.drop_rust_box — Method
drop_rust_box(box::RustBox{T}) where T

Drop a RustBox, calling the appropriate Rust drop function. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.

source
RustCall.drop_rust_rc — Method
drop_rust_rc(rc::RustRc{T}) where T

Drop a RustRc, decrementing the reference count. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.

source
RustCall.drop_rust_vec — Method
drop_rust_vec(vec::RustVec{T}) -> Nothing

Drop a RustVec by calling the Rust-side drop function. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.

source
RustCall.flush_deferred_drops — Method
flush_deferred_drops() -> Int

Attempt to free all deferred pointers using the Rust helpers library. Returns the number of successfully freed pointers. Call this after rebuilding/reloading the helpers library.

source
RustCall.get_deferred_drop_count — Method
get_deferred_drop_count() -> Int

Return the number of ownership objects waiting for deferred deallocation. A non-zero value indicates objects that could not be freed because the Rust helpers library was unavailable at drop time.

source
RustCall.get_rust_helpers_lib — Method
get_rust_helpers_lib() -> Union{Ptr{Cvoid}, Nothing}

Get or load the Rust helpers library. This library provides FFI functions for Box, Rc, Arc operations. Returns nothing if the library is not available.

source
RustCall.get_rust_helpers_lib_path — Method
get_rust_helpers_lib_path() -> Union{String, Nothing}

Path to the ownership helper library built by Pkg.build("RustCall"), or nothing when no copy of it exists.

Every candidate location, and their order, is native_product_candidates (#258): RUSTCALL_HELPERS first, then this package tree's own build directory — a scratch space for an installed package, deps/rustcall_helpers/target for a checkout — then the legacy in-package locations a pre-v0.3.5 build left behind. The pre-v0.4 name librust_helpers and the alias RUSTCALL_RUST_HELPERS (#387) stopped being looked for in v0.5 (#417): a tree built by v0.3.x is rebuilt once with Pkg.build("RustCall").

source
RustCall.require_rust_helpers — Method
require_rust_helpers(operation) -> Ptr{Cvoid}

The ownership helper library's handle, or a refusal that says exactly how to get one.

Every RustBox / RustRc / RustArc / RustVec / RustSlice operation goes through here before it allocates anything (#249). Refusing up front is the whole point: a value constructed without the library has no way to free itself, so the alternative to an error at construction is a leak, or a finalizer that calls into a library that is not there.

The message names the operation and the one command that fixes it, because "Rust helpers library not loaded" alone leaves the reader to guess whether they must install Rust, rebuild the package, or restart Julia.

source
RustCall.rust_vec_get — Method
rust_vec_get(vec::RustVec{T}, index::Integer) -> T

Get an element from RustVec using Rust FFI with 0-based indexing.

Arguments

  • vec::RustVec{T}: The RustVec to access
  • index::Integer: 0-based index of the element to retrieve

Returns

  • T: The element at the specified index

Throws

  • ErrorException: If the vec has been dropped
  • BoundsError: If index is out of bounds
  • ErrorException: If the Rust helpers library is not loaded

Example

rust_vec = create_rust_vec(Int32[10, 20, 30])
value = rust_vec_get(rust_vec, 0)  # Returns 10
value = rust_vec_get(rust_vec, 2)  # Returns 30
drop!(rust_vec)

Note

This function uses 0-based indexing to match Rust's convention. For 1-based indexing, use vec[i] syntax instead.

See also: rust_vec_set!, getindex

source
RustCall.rust_vec_set! — Method
rust_vec_set!(vec::RustVec{T}, index::Integer, value::T) -> Bool

Set an element in RustVec using Rust FFI (0-indexed). Returns true if successful.

source
RustCall.safe_dlsym — Method
safe_dlsym(lib::Ptr{Cvoid}, sym::Symbol) -> Ptr{Cvoid}

Look up a symbol in a shared library, raising a clear error instead of returning NULL (which would cause a segfault when passed to ccall).

source
RustCall.to_julia_vector — Method
to_julia_vector(vec::RustVec{T}) -> Vector{T}

Convert a RustVec to a new Julia Vector using efficient Rust FFI copy.

This is the recommended way to convert RustVec data to Julia when you don't have a pre-allocated buffer.

Arguments

  • vec::RustVec{T}: The RustVec to convert

Returns

  • Vector{T}: A new Julia Vector containing a copy of the data

Throws

  • ErrorException: If the vec has been dropped

Example

rust_vec = create_rust_vec(Int32[1, 2, 3, 4, 5])
julia_vec = to_julia_vector(rust_vec)
@assert julia_vec == Int32[1, 2, 3, 4, 5]
drop!(rust_vec)

Note

This function allocates a new Julia Vector. If you already have a buffer, use copy_to_julia! instead for better performance.

See also: copy_to_julia!, create_rust_vec

source
RustCall.try_load_rust_helpers — Method
try_load_rust_helpers() -> Bool

Try to load the Rust helpers library. Returns true if successful, false otherwise. This function will not throw errors, making it safe to call during module initialization.

source
RustCall.verify_rust_helpers_functions — Method
verify_rust_helpers_functions(lib::Ptr{Cvoid}) -> Bool

Verify that required functions are available in the loaded library. Returns true if all required functions are found, false otherwise.

source

#[julia] structs (src/ffi/structs.jl)

RustCall.FINALIZER_FREE_FAILURES — Constant
FINALIZER_FREE_FAILURES

Number of destructor calls that raised inside a finalizer, process-wide.

A finalizer must not log: @warn allocates, can yield, and runs at a moment the program did not choose. Counting is allocation-free and lock-free, and finalizer_failure_count() makes the number observable to a test or a user who suspects a leak.

source
RustCall.PyO3Shape — Type
PyO3Shape(kind, name = "", rank = 0, inner = nothing)

What a value of a PyO3 item's argument, return or property is to the Python-host bindings, as the extractor resolved it from the type's paths (manifest py_shape / py_return, rustcall_julia_core::manifest::PyShape; #264, PR #525 review). Julia never reads the Rust spelling for this.

kind is :class (name the class's Rust name, Self already resolved), :vec / :option (inner the element), :array (a pyo3-numpy array, name the element primitive, rank its rank or -1), :scalar (name the primitive), :string, :unit, :injected (supplied by the interpreter) or :opaque (passed and returned as the Python object it is).

source
RustCall.RustHandleArg — Type
RustHandleArg(ffi_name, module_path, name)

The #[julia] struct an argument borrows (&Value, &Self, &mut a::Value; manifest Arg.abi "handle" / "handle_mut" with Arg.handle, #565): its Struct.ffi_name, and the module path and Rust name Julia binds its handle type under. The wrapper takes the reference as written, which is one thin pointer in the C ABI, so the Julia wrapper passes the pointer its handle object owns (_string_arg_plan), never the object by value.

source
RustCall.RustMethod — Type
RustMethod

A method of a #[julia] struct as recorded in the manifest.

  • symbol: exported wrapper symbol (rustcall_<Struct>_<method>, #279); empty for generic structs, and for a method built by hand rather than read from a manifest, where the emitters fall back to method_wrapper_symbol
  • is_constructor: an inherent method returning Self / the struct type, from the manifest (never from the name: a fn new() -> i32 is not one, PR #513 review)
  • returns_boxed_struct: the wrapper boxes the result and returns *mut Struct (manifest Method.returns_boxed_struct, schema 4). Julia used to re-derive this by comparing return_type against "Self" (#276)
  • generic_wrapper: generic wrapper source registered for monomorphization
  • generic_wrapper_name: the name that wrapper is registered under (<ffi_name>_<method>, module-qualified, #462), stated by the manifest
  • attribute: the attribute of the impl block the method came from — :julia, :py_methods for a scanned #[pymethods] block, :none for an inline-mode impl (which carries none) or a hand-built method. It need not be the struct's own (#275 Phase 3)
  • string_owner: the stem the wrapper's string buffers hang off (<owner>_RustCallOwnedString, <owner>_free_rust_string), stated by the manifest rather than derived from the flavour (#342). Empty when the manifest states none; see _method_string_owner
  • arg_names: the Julia parameter names of the arguments after self — julia_parameter_names of the Rust names, applied by the constructor (#516)
  • arg_slice_elements / arg_slice_lengths: per argument, the manifest representation and length slot for slice / slice_mut borrows (#570)
  • arg_handles: per argument, the #[julia] struct it borrows (RustHandleArg, #565), or nothing
source
RustCall.RustStructInfo — Type
RustStructInfo

A #[julia] / #[derive(JuliaStruct)] struct as recorded in the manifest.

  • fields: (name, rust_type) for every named field
  • field_abis: manifest Field.abi per field — "string" for an owned UTF-8 buffer, "vec" for an owned RustVec buffer, "" when returned as written
  • field_vec_elements / field_free_symbols: the element type and exact allocator-matched release export of a "vec" getter (schema 10, #303)
  • field_getters / field_setters: exported accessor symbols per accessible field
  • context_code: struct + impl source (generic structs only)
  • generic_wrappers: (name, source, type_params) wrappers registered for monomorphization; type_params are the wrapper's own parameter names in the struct's parameter order (impl<U> Wrapper<U> wrappers list U where the struct declares T)
  • has_owned_string_helper / has_borrowed_string_helper: whether the <Struct>_RustCallOwnedString / <Struct>_RustCallBorrowedString ABI helpers exist
source
RustCall._call_generic_constructor — Method
_call_generic_constructor(func_name, struct_name, args, types) -> (ptr, lib_name, gen)

Run a generic constructor and hand back the pointer and the snapshot the object it allocated must capture.

struct_name is the struct's FFI name (RustStructInfo.ffi_name): the destructor it looks for is <ffi_name>_free, module-qualified like the constructor (#462).

The generic-struct group specializes the constructor, methods, accessors, and <Struct>_free into the constructor's image, so one instantiation has one allocator and one liveness flag. The symbol lookup below remains a fallback for hand-registered generic functions that predate grouped registration.

caller is the module whose generated constructor this is. The constructor registration is resolved from it (_generic_struct_snapshot): the defining module's own block first, so a same-named struct of another module is never the one constructed (#522).

source
RustCall._call_generic_method_owned — Method
_call_generic_method_owned(lib, func, ptr, args, types, alive) -> (ptr, lib, gen)

The instance-method counterpart of _call_generic_constructor: call a method of a generic struct whose Rust wrapper returns *mut Self, and hand back the new allocation together with the generation that allocated it — its destructor, liveness flag and panic channel (#592).

source
RustCall._call_rust_constructor — Method
_call_rust_constructor(lib_name, func_name, struct_name, args...) -> (ptr, target)

Run a constructor (or a Self-returning method) and hand back both the allocated pointer and the snapshot it came from.

The object built from ptr must capture the destructor and the liveness flag of the generation that allocated it. Taking them afterwards — even immediately afterwards — is a second lookup by library name, and a reload in between binds a pointer from the retired image to the replacement's free (#277).

source
RustCall._check_generic_borrows — Method
_check_generic_borrows(self, struct_name, receiver_mutable, args, mutables)

Check that a generic struct's method may lend args to Rust as &Vec2<T> / &mut Vec2<T> alongside its receiver (#591): every argument carries the receiver's handle type, is alive, and comes from the same library image, and no borrow overlaps another when at least one of the two is exclusive. mutables[i] says whether args[i] is a &mut borrow; receiver_mutable whether the receiver is &mut self. Two shared borrows may alias — Rust allows that — but a &mut borrow may not overlap the receiver or another argument, which would create overlapping references involving an exclusive one (#591 review).

source
RustCall._default_payload_abi — Method
_default_payload_abi(payload_type) -> String

The ok_abi / err_abi / inner_abi of a hand-built signature (tests, legacy callers). The extractor classifies the payload on the Rust side (rustcall_julia_core::codegen::payload_abi); this reconstructs the column from the same FFI contract the wrapper generators consult, so a hand-built signature and a manifest one agree. &str is included: a payload is always copied into an owned buffer, never borrowed.

source
RustCall._default_return_abi — Method
_default_return_abi(return_type, arg_abis) -> String

The return_abi for methods constructed by hand: a String return is an owned buffer, a &str return is borrowed unless the method also takes string arguments, in which case the wrapper copies it (see rustcall_julia_core::codegen::return_abi).

source
RustCall._generic_constructor_params — Method
_generic_constructor_params(struct_name, params, wrapper_params, arg_rust_types, args)
    -> Tuple

The struct parameters a bare constructor call Vec2(x, y) pins (#593): each argument whose Rust type is exactly a parameter contributes typeof(arg). All parameters must be pinned, and two arguments pinning one parameter must agree — otherwise the call is refused by name rather than guessing a parameter the constructor cannot know.

wrapper_params are the constructor wrapper's parameter names in the struct's parameter order (impl<U> Pair<U> gives (:U,) for a struct Pair<T>); an argument type is read in that namespace and renamed to params first, so a wrapper that names its parameters differently still pins them (review).

source
RustCall._generic_method_wrapper_name — Method
_generic_method_wrapper_name(info::RustStructInfo, m::RustMethod) -> String

The name the generic wrapper of m, a method of the generic struct info, is registered and monomorphized under.

The manifest states it (Method.generic_wrapper_name, #462): the extractor names every wrapper of a generic struct off its FFI name, module path folded in (a__Pair_new), so two same-named generic structs in different modules of one block register different wrappers. Deriving it from info.name here — as Julia did before — gave both Pair_new, and the second registration replaced the first. The fallback is for a hand-built RustMethod, which states none; it uses the same scheme on the FFI name, never the bare name.

source
RustCall._generic_owned_result — Method
_generic_owned_result(ptr, lib, handle, generation, struct_name, types, snapshot)
    -> (ptr, lib_name, gen)

The generation an object allocated by a generic-struct constructor or by an instance method returning the struct must capture: its destructor, its liveness flag and its panic channel, all from the image that allocated it (#249, #277, #592). snapshot is the constructor's (or the method's) group.

source
RustCall._generic_struct_free_target — Method
_generic_struct_free_target(free_name, types) -> (free_ptr, lib_name, handle, generation, channel)

The destructor of one instantiation of a generic #[julia] struct, resolved by monomorphizing it at construction time, together with the image it came from.

The specialization has to be compiled before the finalizer needs it, because monomorphizing from inside a finalizer would shell out to the extractor, invoke rustc, and take REGISTRY_LOCK. Here the pointer is not merely warmed up but captured, so the finalizer never consults a registry at all.

Not called directly by generated code: generic_struct_generation_snapshot pairs the pointer with the liveness flag of handle under one lock, which is the value a constructor may capture.

(C_NULL, "", C_NULL, 0, C_NULL) when the generic destructor is not registered — a struct whose _free wrapper the extractor did not emit.

caller is the module whose generated code asks — the one that defines the struct — and the destructor is its own (_generic_struct_snapshot, #522); nothing takes the bare-name registration.

source
RustCall._generic_struct_owner — Method
_generic_struct_owner(mod, block) -> Union{String, Nothing}

The library mod recorded for the rust""" block block, by the block's content (source, cfg snapshot, compiler settings, Cargo environment) rather than a library name: a precompiled caller's block may be reloaded under another name, and _resolve_lib renames the record with it (#522). Restores the module's blocks first, as every generated call does. nothing when the module records no such block.

source
RustCall._generic_struct_snapshot — Method
_generic_struct_snapshot(caller, name; block = nothing) -> Union{GenericStructSnapshot, Nothing}

The registration of the generic struct wrapper name that the generated code of the struct reaches — the member its defining block registered (#522) — together with its whole group, read in one transaction (_read_generic_struct_snapshot). Every later step of the call uses that snapshot; nothing reads the member or its group by name again, so an unload racing the call can leave it with the whole group or none of it, never a part (PR #523 review).

block is that block's RustBlockSnapshot, spliced into the generated code by emit_julia_definitions; _generic_struct_owner finds the library caller recorded for it — after _resolve_lib, so a precompiled or reloaded block is restored and found under whatever name it now has — and the member is read from that library's own rows, GENERIC_FUNCTIONS_BY_LIB[(owner, name)]. This is not name resolution: another block of the module exporting an ordinary function of the same name (#[no_mangle] fn Boxed_new), or another module's struct of the same name, has no say in it.

The bare-name registration is read only when no owner is known: a call without caller or block, or a module that records no such block. Once the owner is known its row is the only answer. A row can vanish between finding the owner and reading it — another task unloaded the library, dropping its rows — so the lookup is retried, each attempt restoring the module's blocks again; if the row is still missing, this raises a RustError rather than reading the bare name, which may be another module's same-named struct with another layout (PR #523 review).

source
RustCall._inline_boxed_result_body — Method
_inline_boxed_result_body(info, m, wrapper_name, esc_struct, bindings, preserved,
                          call_args, frame, lib, leading_args) -> Expr

The body of an inline wrapper whose Result<Self, E> stores a boxed Ok (Method.ok_abi == "boxed"): a fallible constructor (#559) or any other method returning the struct in a Result (#564). One snapshot supplies the wrapper, its channel and the destructor and liveness flag the new object carries, so the object is bound to the image that allocated it; the image must export the boxed-Ok marker, since an older macro returned Self by value. lib is the library expression, leading_args the receiver's pointer, if any.

source
RustCall._inline_method_payload_wrapper — Method
_inline_method_payload_wrapper(info, m, fname, wrapper_name, esc_args, bindings,
                               preserved, call_args; self) -> Expr

The Julia wrapper of an inline #[julia] struct method returning Result<T, E> / Option<T> (#268).

Identical in shape to the free-function wrapper in src/macros/julia_functions.jl: one generation snapshot (pointer, panic channel and — when a payload is an owned string — the <owner>_free_rust_string of the buffer the wrapper used), the aggregate read by value, the panic channel consulted before anything is decoded, and only the active payload converted and released.

self is the escaped struct type for an instance method and nothing for a static one. The owner of the string buffer comes from the manifest (_method_string_owner): the struct for a method wrapped next to it, the method itself for one whose #[julia] impl block sits in another module (#342).

source
RustCall._method_string_owner — Method
_method_string_owner(m::RustMethod, fallback) -> String

The stem m's string buffers hang off: <owner>_RustCallOwnedString for an owned String result or payload, released through <owner>_free_rust_string, and <owner>_RustCallBorrowedString for a borrowed &str.

The manifest states it per method (Method.string_owner, schema 8, #342 — a breaking addition, because a consumer that ignores the column releases a cross-module method's buffer through a symbol the library does not export), because one inline manifest can hold both shapes: a method whose #[julia] impl block sits beside its struct shares the struct's buffers, one whose block sits in another module has its wrapper — and its buffers — emitted at the block. Deriving the owner from the flavour, as Julia did before #342, would look for <Struct>_free_rust_string where the library exports <Struct>_<method>_free_rust_string.

fallback is the flavour's historical derivation, used for a hand-built RustMethod and for a manifest entry that states no owner (a scanned #[pymethods] method, a generic struct's methods).

source
RustCall._prepare_generic_struct_wrappers — Method
_prepare_generic_struct_wrappers(info, expanded_source; compiler, cargo, lib_name)
    -> Vector{GenericFunctionInfo}

The member registrations of a generic struct, prepared outside any lock (it may run the extractor), owned by lib_name. _register_manifest installs them with the rest of the library's metadata, in the one transaction that publishes the library (install_library_metadata!, #522): an owner's rows are then all there or none is, which _read_generic_struct_snapshot relies on. Empty for a non-generic struct.

source
RustCall._read_generic_struct_snapshot — Method
_read_generic_struct_snapshot(owner, key) -> Union{GenericStructSnapshot, Nothing}

The one read of the generic registrations on a generic struct's path (#522), in one REGISTRY_LOCK transaction: the member key and every member of its group. With an owner, both come from that library's own rows of GENERIC_FUNCTIONS_BY_LIB — installed and dropped with the library in one transaction, so they are all there or none is — and a missing member is nothing, never the bare name. Without one, the bare-name registration and its owner's group (_generic_group_members), as monomorphize_function(name) reads them.

source
RustCall._result_payload — Method
_result_payload(SurfaceType, value, free_ptr) -> value

Read one Result / Option payload out of the #[repr(C)] aggregate a wrapper returned (#268).

A plain payload is the C slot Rust stored, converted to the surface type (convert_return, which is the identity for everything but char). A CRustString payload is an owned buffer the wrapper allocated: it is copied into a Julia String and released through free_ptr, the <owner>_free_rust_string of the very call that produced it — taken from the same generation snapshot, so the buffer is never handed to another image's allocator (#277).

Only the active payload is ever passed here. The inactive one is MaybeUninit::zeroed() on the Rust side, so reading it would be undefined and freeing it would be a double free.

source
RustCall._static_method_collisions — Method
_static_method_collisions(functions, structs) -> Set{String}

The names a static (non-constructor) method shares with a free function or with another struct's static method, among the items one generated module (a rust""" block, or a crate) defines. Such a name gets no bare name(args...) form — only the type-dispatched name(Struct, args...) — so two definitions never overwrite each other (#323). Free functions always keep their bare name.

source
RustCall._take_owned_string — Method
_take_owned_string(raw::CRustString, free_ptr) -> String

Copy an owned Rust string buffer into a Julia String and release it. A null buffer (the panic sentinel, and the zeroed inactive payload) owns nothing and is not released.

source
RustCall.artifact_generation_snapshot — Method
artifact_generation_snapshot(lib_name, struct_name) -> ArtifactGeneration

The destructor of struct_name and the liveness flag of the image that exports it, from one generation. The handle and flag are captured together; a cold destructor pointer is resolved on that handle outside STATE.

This is what a #[julia] struct captures at construction so its finalizer needs no lookup (#249). The two must come from the same generation: taken separately, an object could capture the destructor of the image that allocated it and the liveness flag of the image that replaced it, and would then either skip a free it should have made or make one into an image that had been closed.

The destructor is resolved on that library's own handle, never through the cross-library fallback: each cdylib links its own allocator shim, so borrowing another library's <Struct>_free is undefined behaviour dressed up as a convenience (the allocator contract in docs/src/panics.md).

A missing destructor is C_NULL, which makes the finalizer a no-op: a leak rather than a free through the wrong allocator.

source
RustCall.check_not_freed — Method
check_not_freed(obj, type_name)

Raise when the object was finalized or its captured library image was closed.

Without it the call dereferences C_NULL inside Rust, which is a segfault rather than an error message, or enters a retained pointer in an unmapped image. This check does not make closing concurrently with a call safe: an explicit close still requires quiescence. The inline structs got this in #277 Phase B4; @rust_crate structs have had it since #246 (_check_not_freed).

source
RustCall.emit_julia_definitions — Method
emit_julia_definitions(info::RustStructInfo; colliding = Set{String}())

Generate Julia code to define a corresponding mutable struct and its methods. Only generates definitions for structs marked with #[derive(JuliaStruct)] or #[julia]. colliding is _static_method_collisions of the whole block: a static method whose name is in it gets no bare name(args...) form (#323). block is the defining block's RustBlockSnapshot, spliced into a generic struct's generated code so that its members are looked up under the library that block loaded (_generic_struct_snapshot, #522).

source
RustCall.field_is_writable — Method
field_is_writable(info::RustStructInfo, field_name) -> Bool

Whether the manifest recorded an exported setter for the field. Independent of field_is_accessible: a #[pyclass] field marked #[pyo3(set)] alone is writable and not readable, and the crate emitters give it a setproperty! branch and no getproperty one (#307 review).

source
RustCall.finalize_rust_object! — Method
finalize_rust_object!(x)

The body every generated #[julia] struct finalizer runs.

The order is the contract:

  1. read the pointer; a null one means this object was already finalized, or was never given one, so there is nothing to do;
  2. null the field before the call, so a second finalization — or a concurrent one — cannot free the same allocation twice;
  3. bail out if the library is gone: unload_artifact! flipped the captured liveness flag, and calling into a dlclosed image is a jump into freed text, which is worse than the leak;
  4. call the captured destructor and immediately consume its captured panic channel, counting rather than logging a failure.

No lock, no lookup, no allocation on the success path.

source
RustCall.finalizer_failure_count — Method
finalizer_failure_count() -> Int

How many times a Rust destructor raised while being called from a finalizer. Non-zero means objects were leaked; the usual cause is a library unloaded without unload_library (which retires its objects properly).

source
RustCall.generic_struct_generation_snapshot — Method
generic_struct_generation_snapshot(free_name, types, fallback_lib) -> ArtifactGeneration

The generic counterpart of artifact_generation_snapshot: the instantiated destructor of a generic #[julia] struct and the liveness flag of the image that exports it, as one value.

Monomorphizing can run the extractor and rustc, so it happens first and outside the lock. What matters is that the flag is then found by the handle the pointer came from (alive_ref_for_handle), not by the library's name: if that image has since been retired the object gets the retired image's own flag — which is flipped when the image is closed, which is exactly when the destructor stops being callable — and if it is gone entirely the object goes inert and leaks rather than calling into unmapped memory.

caller, the module that defines the struct, picks whose destructor it is when two modules define a generic struct of the same name (#522).

source
RustCall.method_wrapper_symbol — Method
method_wrapper_symbol(struct_name, method::RustMethod) -> String

The exported symbol the Julia wrapper of a concrete struct method calls.

Manifest-backed methods carry it in symbol (rustcall_<Struct>_<method> since #279). The six-argument RustMethod constructor cannot know the struct name, so a hand-built method records none; rather than emit _get_func_ptr("") the symbol is derived from the same scheme here. Generic structs never take this path: their wrappers are monomorphized by name and are addressed through generic_wrapper, not through a symbol.

source
RustCall.register_generic_struct_wrappers — Method
register_generic_struct_wrappers(info::RustStructInfo, expanded_source::String)

Register the generic wrapper functions of a generic #[julia] struct for on-demand monomorphization. The extractor emits the (unexported) generic wrappers into the expanded source next to the struct, so the registered code is the whole expanded block and each wrapper is addressed by its qualified name (module::Struct_method); specialize then instantiates it in place with every module-scoped name available. Non-generic structs have their wrappers compiled into the library directly and need no registration.

lib_name is the library of the block that defines the struct: it owns the registration (GenericFunctionInfo.owner), so another module's struct of the same name — same group, same wrapper names — neither replaces these members nor joins their instantiation, and the struct's generated code reads its own members from this library's rows (_generic_struct_snapshot, #522). nothing registers without an owner.

source
RustCall.struct_free_pointer — Method
struct_free_pointer(lib_name, struct_name) -> Ptr{Cvoid}

The destructor of struct_name in lib_name, resolved now so the finalizer never has to.

Resolved on that library's own handle, never through the cross-library fallback search get_function_pointer performs. An allocation made by one library must be released by the same library — each cdylib links its own allocator shim — so borrowing another library's <Struct>_free because this one happens not to export it would be undefined behaviour dressed up as a convenience (the allocator contract in docs/src/panics.md).

C_NULL when the library does not export one — a struct whose destructor was #[cfg]-ed out, or a hand-registered RustStructInfo with no library behind it. A null destructor means the finalizer does nothing, which leaks rather than crashes: the right trade for a lookup that has already failed.

source