module Rubellite::Docs::B_ADVANCED_FEATURES::C_API_AND_MEMORY

Overview

C API, Memory Management & GC Coordination

Interfacing Crystal with CRuby requires managing two concurrent runtimes, each equipped with its own garbage collector: Crystal's Boehm-Demers-Weiser GC and Ruby's compacting generational GC.

Rubellite implements strict memory safety protocols and Windows MSVC import isolation to eliminate memory corruption, symbol collisions, and dangling references.

Executive Summary & Key Topics

Topic Method / Anchor Description
Dual-GC Pinning Protocol .topic_01_gc_pinning Protecting Ruby objects held inside Crystal memory structures.

Related Guides & Source References

Defined in:

rubellite/docs/b_advanced_features/c_api_and_memory.cr

Class Method Summary

Class Method Detail

def self.topic_01_gc_pinning : Nil #

Dual-GC Pinning Protocol: Protecting Ruby objects held inside Crystal memory structures.

Whenever a Crystal struct or class holds a long-lived reference to a LibRuby::Value, it must be registered with the Ruby GC to prevent the Ruby collector from sweeping or moving it.

Mechanism Function Purpose
**Root Registration** `rb_gc_register_address` Pins a pointer address to prevent GC collection
**Unregistration** `rb_gc_unregister_address` Releases the GC root when the Crystal object finalizes
**Temporary Protection** `Rubellite::GC.protect { ... }` Protects local values across complex allocations

Working Examples

require "rubellite"

# Safe allocation with automatic GC pinning
ref = Rubellite::GC.pinned_value(Rubellite.eval("[1, 2, 3]"))
# ref is guaranteed not to be moved or collected by CRuby GC
ref.free # Cleanly unregisters from GC roots

Common Pitfalls & Safety Caveats

  • Warning: Never pass unpinned Ruby pointers across long-lived Crystal Channels without pinning.
  • Warning: On Windows, always link with ext/ruby_clean.lib to prevent clashing with ucrt symbol definitions.

Frequently Asked Questions (FAQ)

  • Q: What is ruby_clean.lib? A: A sanitized import library generated by Rubellite's import_lib_generator to filter out conflicting Win32 symbols.

[View source]