0

I'm trying to write a really small C extension. So I don't want to make a whole ruby class, with initializer, allocator, and so forth. All I want to do is add a static method to an existing class, method which will run an algorithm and return a result. Unfortunately, all documentation I find only speak about wrapping a C struct into a VALUE, but that's not my use case.

What I want to know : if I create a ruby object (which will allocate memory) inside my C code, and that I return it as the result of my function, will it be taken care of properly by the garbage collector, or is it going to leak ?

Example :

void Init_my_extension() 
{
  VALUE cFooModule;

  cFooModule = rb_const_get(rb_cObject, rb_intern("Foo"));
  rb_define_singleton_method(cFooModule, "big_calc", method_big_calc, 1);
}

VALUE method_big_calc(VALUE self, VALUE input)
{
  VALUE result;

  result = rb_ary_new();

  return result;
}

Will the array that was allocated by rb_ary_new() be properly cleaned when it's not used anymore ? How is the garbage collector aware of references to this value ?

Quentin
  • 1,085
  • 1
  • 11
  • 29

1 Answers1

0

Yes, You code properly clean memory if You using rb_ary_new().

In my opinion You need answer on other question. How create you own object. http://www.onlamp.com/pub/a/onlamp/2004/11/18/extending_ruby.html

first You must create rb_define_alloc_func(cYouObject,t_allocate);

similar this

struct stru { char a; };

void t_free(struct stru *a) { }

static VALUE t_allocate(VALUE obj) { return Data_Wrap_Struct(obj,NULL,t_free,m); }

Marko Lustro
  • 173
  • 1
  • 10