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 arrayNote
This creates a copy of the data. Modifications to the returned Vector will not affect the original RustVec.
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
endRustCall.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
RustBoxowns 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)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.
RustCall.RustPtr — Type
RustPtr{T}A pointer to a Rust value of type T. Corresponds to *const T or *mut T in Rust.
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
cloneto create new references - Call
drop!to decrement reference count
Note
Rc<T> is not thread-safe. For multi-threaded scenarios, use RustArc{T}.
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.
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.
RustCall.RustSlice — Type
RustSlice{T}Represents Rust's slice type &[T] - a borrowed view into a contiguous sequence.
Fields
ptr: Pointer to the first elementlen: Number of elements
Note
This is a borrowed reference; the underlying data must outlive the slice.
RustCall.RustStr — Type
RustStrRepresents Rust's string slice &str. This is a borrowed reference, so the memory is managed elsewhere.
RustCall.RustString — Type
RustStringRepresents 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.
RustCall.RustVec — Type
RustVec{T}Represents Rust's Vec<T> type - a growable array.
Fields
ptr: Pointer to the datalen: Number of elementscap: 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)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.
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 arrayBase.getindex — Method
getindex(slice::RustSlice{T}, i::Int) -> TGet the element at index i in a RustSlice.
Arguments
slice: The RustSlice to index intoi: The index (1-based, like Julia arrays)
Example
slice = RustSlice{Int32}(ptr, 10)
value = slice[1] # Get first elementNote
This performs bounds checking. The index must be between 1 and length(slice).
Base.getindex — Method
getindex(vec::RustVec{T}, i::Int) -> TGet the element at index i in a RustVec.
Arguments
vec: The RustVec to index intoi: The index (1-based, like Julia arrays)
Example
vec = RustVec{Int32}(ptr, 10, 20)
value = vec[1] # Get first elementNote
This performs bounds checking. The index must be between 1 and length(vec).
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)
endBase.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)
endBase.setindex! — Method
setindex!(vec::RustVec{T}, value, i::Int) -> valueSet the element at index i in a RustVec to value.
Arguments
vec: The RustVec to modifyvalue: 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 42Note
This performs bounds checking. The index must be between 1 and length(vec).
RustCall.cstring_to_julia_string — Method
cstring_to_julia_string(cs::Cstring) -> StringConvert a Cstring (from Rust) to a Julia String. This copies the data.
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.
RustCall.is_dropped — Method
is_dropped(x::Union{RustBox, RustRc, RustArc, RustVec}) -> BoolCheck if an ownership type has been dropped.
RustCall.is_err — Method
is_err(result::RustResult)Check if a RustResult is Err.
RustCall.is_none — Method
is_none(option::RustOption)Check if a RustOption is None.
RustCall.is_ok — Method
is_ok(result::RustResult)Check if a RustResult is Ok.
RustCall.is_some — Method
is_some(option::RustOption)Check if a RustOption is Some.
RustCall.is_valid — Method
is_valid(box::RustBox) -> BoolCheck if a RustBox is still valid (not dropped and not null).
RustCall.julia_string_to_cstring — Method
julia_string_to_cstring(s::String) -> StringPrepare a Julia String for FFI (to be converted to Cstring by ccall). Note: The actual conversion happens at ccall time via cconvert/unsafe_convert.
RustCall.julia_string_to_rust — Method
julia_string_to_rust(s::String) -> RustStrConvert 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.
RustCall.rust_str_to_julia — Method
rust_str_to_julia(rs::RustStr) -> StringConvert a RustStr (string slice) to a Julia String. This copies the data.
RustCall.rust_string_to_julia — Method
rust_string_to_julia(rs::RustString) -> StringConvert a RustString to a Julia String. This copies the data from Rust memory to Julia memory.
RustCall.snake_to_pascal — Method
snake_to_pascal(s::AbstractString) -> StringConvert 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"RustCall.unwrap — Method
unwrap(option::RustOption)Unwrap a RustOption, returning the Some value or throwing an error.
RustCall.unwrap — Method
unwrap(result::RustResult)Unwrap a RustResult, returning the Ok value or throwing an error.
RustCall.unwrap_or — Method
unwrap_or(result::RustResult{T, E}, default::T)Unwrap a RustResult, returning the Ok value or the provided default.
RustCall.unwrap_or — Method
unwrap_or(option::RustOption{T}, default::T)Unwrap a RustOption, returning the Some value or the provided default.
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.
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.
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.
RustCall.clone — Method
clone(arc::RustArc{T}) -> RustArc{T} where TClone a RustArc, incrementing the atomic reference count.
RustCall.clone — Method
clone(rc::RustRc{T}) -> RustRc{T} where TClone a RustRc, incrementing the reference count.
RustCall.copy_to_julia! — Method
copy_to_julia!(vec::RustVec{T}, dest::Vector{T}) -> IntCopy 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 fromdest::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 droppedErrorException: 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
RustCall.create_rust_arc — Method
create_rust_arc(value::T) -> RustArc{T} where TCreate a RustArc from a Julia value. Automatically calls the appropriate Rust Arc::new function.
RustCall.create_rust_box — Method
create_rust_box(value::T) -> RustBox{T} where TCreate a RustBox from a Julia value. Automatically calls the appropriate Rust Box::new function.
RustCall.create_rust_rc — Method
create_rust_rc(value::T) -> RustRc{T} where TCreate a RustRc from a Julia value. Automatically calls the appropriate Rust Rc::new function.
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 loadedErrorException: 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 doneNote
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!
RustCall.deferred_drop_count — Method
deferred_drop_count() -> IntReturn the number of pointers awaiting deferred deallocation.
RustCall.drop_rust_arc — Method
drop_rust_arc(arc::RustArc{T}) where TDrop a RustArc, decrementing the atomic reference count. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.
RustCall.drop_rust_box — Method
drop_rust_box(box::RustBox{T}) where TDrop a RustBox, calling the appropriate Rust drop function. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.
RustCall.drop_rust_rc — Method
drop_rust_rc(rc::RustRc{T}) where TDrop a RustRc, decrementing the reference count. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.
RustCall.drop_rust_vec — Method
drop_rust_vec(vec::RustVec{T}) -> NothingDrop a RustVec by calling the Rust-side drop function. An atomic claim synchronizes with the GC finalizer; drop_lock serializes explicit drops.
RustCall.flush_deferred_drops — Method
flush_deferred_drops() -> IntAttempt 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.
RustCall.get_deferred_drop_count — Method
get_deferred_drop_count() -> IntReturn 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.
RustCall.get_max_deferred_drops — Method
get_max_deferred_drops() -> IntReturn the current maximum deferred drop queue size.
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.
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").
RustCall.is_rust_helpers_available — Method
is_rust_helpers_available() -> BoolCheck if the Rust helpers library is available.
RustCall.load_rust_helpers_lib — Method
load_rust_helpers_lib(lib_path::String)Load the Rust helpers library from a file path.
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.
RustCall.rust_vec_get — Method
rust_vec_get(vec::RustVec{T}, index::Integer) -> TGet an element from RustVec using Rust FFI with 0-based indexing.
Arguments
vec::RustVec{T}: The RustVec to accessindex::Integer: 0-based index of the element to retrieve
Returns
T: The element at the specified index
Throws
ErrorException: If the vec has been droppedBoundsError: If index is out of boundsErrorException: 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
RustCall.rust_vec_set! — Method
rust_vec_set!(vec::RustVec{T}, index::Integer, value::T) -> BoolSet an element in RustVec using Rust FFI (0-indexed). Returns true if successful.
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).
RustCall.set_max_deferred_drops — Method
set_max_deferred_drops(n::Int)Set the maximum number of deferred drops before an automatic flush is attempted. Default is 1000.
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
RustCall.try_load_rust_helpers — Method
try_load_rust_helpers() -> BoolTry 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.
RustCall.verify_rust_helpers_functions — Method
verify_rust_helpers_functions(lib::Ptr{Cvoid}) -> BoolVerify that required functions are available in the loaded library. Returns true if all required functions are found, false otherwise.
#[julia] structs (src/ffi/structs.jl)
RustCall.FINALIZER_FREE_FAILURES — Constant
FINALIZER_FREE_FAILURESNumber 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.
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).
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.
RustCall.RustMethod — Type
RustMethodA 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 tomethod_wrapper_symbolis_constructor: an inherent method returningSelf/ the struct type, from the manifest (never from the name: afn new() -> i32is not one, PR #513 review)returns_boxed_struct: the wrapper boxes the result and returns*mut Struct(manifestMethod.returns_boxed_struct, schema 4). Julia used to re-derive this by comparingreturn_typeagainst"Self"(#276)generic_wrapper: generic wrapper source registered for monomorphizationgeneric_wrapper_name: the name that wrapper is registered under (<ffi_name>_<method>, module-qualified, #462), stated by the manifestattribute: the attribute of the impl block the method came from —:julia,:py_methodsfor a scanned#[pymethods]block,:nonefor 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_ownerarg_names: the Julia parameter names of the arguments afterself—julia_parameter_namesof the Rust names, applied by the constructor (#516)arg_slice_elements/arg_slice_lengths: per argument, the manifest representation and length slot forslice/slice_mutborrows (#570)arg_handles: per argument, the#[julia]struct it borrows (RustHandleArg, #565), ornothing
RustCall.RustStructInfo — Type
RustStructInfoA #[julia] / #[derive(JuliaStruct)] struct as recorded in the manifest.
fields:(name, rust_type)for every named fieldfield_abis: manifestField.abiper field —"string"for an owned UTF-8 buffer,"vec"for an ownedRustVecbuffer,""when returned as writtenfield_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 fieldcontext_code: struct + impl source (generic structs only)generic_wrappers:(name, source, type_params)wrappers registered for monomorphization;type_paramsare the wrapper's own parameter names in the struct's parameter order (impl<U> Wrapper<U>wrappers listUwhere the struct declaresT)has_owned_string_helper/has_borrowed_string_helper: whether the<Struct>_RustCallOwnedString/<Struct>_RustCallBorrowedStringABI helpers exist
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).
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).
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).
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).
RustCall._default_payload_abi — Method
_default_payload_abi(payload_type) -> StringThe 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.
RustCall._default_return_abi — Method
_default_return_abi(return_type, arg_abis) -> StringThe 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).
RustCall._generic_constructor_params — Method
_generic_constructor_params(struct_name, params, wrapper_params, arg_rust_types, args)
-> TupleThe 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).
RustCall._generic_method_wrapper_name — Method
_generic_method_wrapper_name(info::RustStructInfo, m::RustMethod) -> StringThe 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.
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.
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.
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.
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).
RustCall._inline_boxed_result_body — Method
_inline_boxed_result_body(info, m, wrapper_name, esc_struct, bindings, preserved,
call_args, frame, lib, leading_args) -> ExprThe 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.
RustCall._inline_method_payload_wrapper — Method
_inline_method_payload_wrapper(info, m, fname, wrapper_name, esc_args, bindings,
preserved, call_args; self) -> ExprThe 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).
RustCall._method_string_owner — Method
_method_string_owner(m::RustMethod, fallback) -> StringThe 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).
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.
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.
RustCall._result_payload — Method
_result_payload(SurfaceType, value, free_ptr) -> valueRead 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.
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.
RustCall._take_owned_string — Method
_take_owned_string(raw::CRustString, free_ptr) -> StringCopy 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.
RustCall.artifact_generation_snapshot — Method
artifact_generation_snapshot(lib_name, struct_name) -> ArtifactGenerationThe 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.
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).
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).
RustCall.field_is_accessible — Method
field_is_accessible(info::RustStructInfo, field_name) -> BoolWhether the manifest recorded an exported getter for the field.
RustCall.field_is_writable — Method
field_is_writable(info::RustStructInfo, field_name) -> BoolWhether 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).
RustCall.finalize_rust_object! — Method
finalize_rust_object!(x)The body every generated #[julia] struct finalizer runs.
The order is the contract:
- read the pointer; a null one means this object was already finalized, or was never given one, so there is nothing to do;
- null the field before the call, so a second finalization — or a concurrent one — cannot free the same allocation twice;
- bail out if the library is gone:
unload_artifact!flipped the captured liveness flag, and calling into adlclosed image is a jump into freed text, which is worse than the leak; - 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.
RustCall.finalizer_failure_count — Method
finalizer_failure_count() -> IntHow 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).
RustCall.generic_struct_generation_snapshot — Method
generic_struct_generation_snapshot(free_name, types, fallback_lib) -> ArtifactGenerationThe 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).
RustCall.method_wrapper_symbol — Method
method_wrapper_symbol(struct_name, method::RustMethod) -> StringThe 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.
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.
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.