Attribute Macro magnus::wrap

source ·
#[wrap]
Expand description

Allow a Rust type to be passed to Ruby, automatically wrapped as a Ruby object.

For more control over the wrapped object, see TypedData.

Attributes

  • class = "..." - required, sets the Ruby class to wrap the Rust type. Supports module paths, e.g. Foo::Bar::Baz.
  • name = "..." - debug name for the type, must be unique. Defaults to the class name.
  • free_immediately - Drop the Rust type as soon as the Ruby object has been garbage collected. This is only safe to set if the type’s Drop implmentation does not call Ruby.
  • size - Report the std::mem::size_of_val of the type to Ruby, used to aid in deciding when to run the garbage collector.

Examples

#[magnus::wrap(class = "RbPoint", free_immediately, size)]
struct Point {
    x: isize,
    y: isize,
}

// the `Point` struct is automatically wrapped in a Ruby `RbPoint` object
// when returned to Ruby.
fn point(x: isize, y: isize) -> Point {
    Point { x, y }
}

// Ruby `RbPoint` objects are automatically unwrapped to references to the
// `Point` structs they are wrapping when this function is called from Ruby.
fn distance(a: &Point, b: &Point) -> f64 {
    (((b.x - a.x).pow(2) + (b.y - a.y).pow(2)) as f64).sqrt()
}

#[magnus::init]
fn init() {
    magnus::define_global_function("point", magnus::function!(point, 2));
    magnus::define_global_function("distance", magnus::function!(distance, 2));
}