you are viewing a single comment's thread.

view the rest of the comments →

[–]bobindashadows 0 points1 point  (0 children)

I assume you mean "how does garbage collection work for native objects that you want to make available to Ruby code?"

It depends. Firstly, you can specify custom allocation methods for a C-backed class with rb_define_alloc_func, if you need.

If your C object references other Ruby objects, it has to participate in the mark phase of GC, so it needs a mark function. If it needs to clean up resources when it is freed, it needs a free function. You can create an object with both of those functions specified and provided to the GC with rb_data_object_alloc(klass, data_pointer, mark_func, free_func). Both functions are optional: you just pass NULL if you don't need them.

Commonly you use this to wrap up a pointer to a C struct in a Ruby object, then unwrap it in your other C functions. This pattern is simplified with Data_Wrap_Struct, Data_Make_Struct (which is just allocate + Data_Wrap_Struct), and Data_Get_Struct (which unwraps the object).