Hacker News new | ask | show | jobs
by pansa2 17 days ago
> The C interface to ruby is just superb.

How does it handle garbage collection? AFAIK GC is the main reason behind Lua's stack-based API: it's designed so that C code never needs to hold a pointer to a Lua object, which means an object will never be garbage-collected while C code is still trying to use it.

OTOH Python does allow C code to hold such pointers - so it requires that code to perform error-prone manual reference-counting.

How does Ruby solve this problem?

1 comments

> How does Ruby solve this problem?

The interpreter keeps track of globals and all stack frames. So it knows what objects are in scope.

If you're creating an object that can contain native ruby values inside it's own opaque structure, then when you define the class that wraps this structure you reference the callback functions you want to be called during GC mark and when the GC frees your object. During the mark callback you simply call rb_gc_mark on any of those internal values so the GC knows they are in scope.

In practice it's quite easy to use and you can find many examples of this. There is no equivalent I'm aware of to mark in lua, but the free callback is effectively equivalent to the __gc metamethod.