#ffi #value #box #structures #pass #error #bindings

value-box

Allows developers to pass Rust-allocated structures over ffi

17 stable releases

2.3.3 Mar 13, 2024
2.3.2 Mar 10, 2023
2.3.0 Feb 7, 2023
2.2.3 Jan 26, 2023
1.1.1 Oct 30, 2022

#333 in Rust patterns

Download history 3/week @ 2024-02-11 19/week @ 2024-02-25 7/week @ 2024-03-03 171/week @ 2024-03-10 21/week @ 2024-03-17 1/week @ 2024-03-24 40/week @ 2024-03-31 9/week @ 2024-04-07 400/week @ 2024-04-14

454 downloads per month
Used in 2 crates

MIT license

30KB
694 lines

ValueBox

Crates.io MIT licensed

ValueBox allows developers to pass Rust-allocated structures over ffi. The value-box crate handles most typical use-cases when creating ffi bindings to rust libraries such as:

  • Return newly allocated Rust structures passing ownership to the caller.
  • Receiving the previously created value box and calling associated functions taking the rust structure by reference, mutable reference, cloning the value or taking the value.
  • Finally, dropping the box with the Rust structure in it.
  • Supports Box<dyn MyTrait>.
  • ValueBox is defined as #[transparent]
  • Error handling via custom Error and Result.

Example:

use value_box::{ReturnBoxerResult, ValueBox, ValueBoxPointer};

#[no_mangle]
pub fn library_object_create() -> *mut ValueBox<MyObject> {
    ValueBox::new(MyObject::new()).into_raw()
}

#[no_mangle]
pub fn library_object_is_something(object: *mut ValueBox<MyObject>) -> bool {
    object
        // with_ref_ok() wraps the returned value into Result:Ok,
        // hence the name
        .with_ref_ok(|object| object.is_something())
        .unwrap_or(false)
}

#[no_mangle]
pub fn library_object_try_something(object: *mut ValueBox<MyObject>) {
    object
        // with_ref() expects the closure to return a Result
        .with_ref(|object| object.try_something())
        .log();
}

#[no_mangle]
pub fn library_object_by_ref(object: *mut ValueBox<MyObject>) {
    object.with_ref_ok(|object| object.by_ref()).log();
}

#[no_mangle]
pub fn library_object_by_mut(object: *mut ValueBox<MyObject>) {
    object.with_mut_ok(|mut object| object.by_mut()).log();
}

#[no_mangle]
pub fn library_object_by_value(object: *mut ValueBox<MyObject>) {
    object.take_value().map(|object| object.by_value()).log();
}

#[no_mangle]
pub fn library_object_by_value_clone(object: *mut ValueBox<MyObject>) {
    object
        .with_clone_ok(|object| object.by_value())
        .log();
}

#[no_mangle]
pub fn library_object_release(object: *mut ValueBox<MyObject>) {
    object.release();
}

#[derive(Debug, Clone)]
pub struct MyObject {}
impl MyObject {
    pub fn new() -> Self {
        Self {}
    }

    pub fn by_ref(&self) {}
    pub fn by_mut(&mut self) {}
    pub fn by_value(self) {}
    pub fn is_something(&self) -> bool {
        true
    }
    pub fn try_something(&self) -> Result<()> {
        Ok(())
    }
}

Dependencies

~0.4–7MB
~24K SLoC