C Extensions, FFI and Embedding

50.1 FFI (No C Compilation Needed)

Fiddle (stdlib) is a lighter alternative.

require "ffi"
module LibC
  extend FFI::Library
  ffi_lib FFI::Library::LIBC
  attach_function :strlen, [:string], :size_t
  attach_function :getpid, [], :int
end
LibC.strlen("hello")    # 5

module LibM
  extend FFI::Library
  ffi_lib "m"
  attach_function :cbrt, [:double], :double
end

50.2 C Extensions

Build with rake-compiler (rake compile). Cross-compile with rake-compiler-dock to ship precompiled native gems.

Rust extensions: magnus + rb-sys (bundle gem --ext=rust). They're safer and increasingly popular (e.g., YJIT itself is written in Rust).

// ext/fast_math/fast_math.c
#include "ruby.h"

static VALUE fast_sum(VALUE self, VALUE ary) {
    long len = RARRAY_LEN(ary);
    double total = 0;
    for (long i = 0; i < len; i++) total += NUM2DBL(rb_ary_entry(ary, i));
    return DBL2NUM(total);
}

void Init_fast_math(void) {
    VALUE mod = rb_define_module("FastMath");
    rb_define_module_function(mod, "sum", fast_sum, 1);
}
# ext/fast_math/extconf.rb
require "mkmf"
create_makefile("fast_math/fast_math")

50.3 Embedding and Interop

Embed CRuby in C apps (ruby_init, rb_eval_string). mruby for embedding in games and devices. JRuby gives full Java interop (java_import). TruffleRuby offers polyglot GraalVM interop. ruby.wasm runs Ruby in the browser/WASI.