Crate rb-sys
The rb-sys crate provides low-level Rust bindings for the Ruby C API, generated directly from ruby.h headers.
Constraints
- Direct
rb-sys: Use for raw,unsafeaccess tolibruby. - Gem Development: For most gem development, prefer higher-level libraries (e.g., Magnus with
rb-sysfeature). See Development Approaches. - Embedding Ruby: Use
rb-syswith thelink-rubyfeature.
Crate Features
The following features can be enabled in your Cargo.toml.
| Feature | Description | Default |
|---|---|---|
gem | Configures the crate for building a Ruby gem (e.g., does not link libruby). | ✅ |
link-ruby | Links libruby for embedding the Ruby VM in a Rust binary. | |
ruby-static | Statically links libruby. Can also be set with the RUBY_STATIC=true env var. | |
global-allocator | Reports Rust memory allocations to the Ruby GC. Recommended for gems. | |
stable-api | Uses Ruby's C-level stable API if available for your Ruby version. | |
bindgen-rbimpls | Includes internal Ruby implementation types in the generated bindings. | |
bindgen-deprecated-types | Includes deprecated Ruby functions and types in the bindings. |
Usage Examples
Ruby Gem Integration
Enable the gem feature (default) and global-allocator for memory reporting.
[dependencies]
rb-sys = { version = "0.9", features = ["global-allocator"] }
Embedding Ruby VM
Enable the link-ruby feature to embed a Ruby VM.
[dependencies]
rb-sys = { version = "0.9", features = ["link-ruby"] }
Ruby Version Compatibility
rb-sys is compatible with Ruby 2.7 and later. The crate detects the Ruby version at compile time and adapts the
bindings accordingly.
For Ruby 3.2 and later, rb-sys provides a ruby_abi_version function that is required for native extensions.
Integration with Magnus
If you're building a Ruby extension, it's recommended to use the Magnus crate on
top of rb-sys. Magnus provides a high-level, safe API for interacting with Ruby:
[dependencies]
magnus = { version = "0.7", features = ["rb-sys"] }
rb-sys = "0.9"