1

Right now I have a series of objects that are created using C extensions, so say they are

  • Foo
  • Bar
  • Baz.

I have ruby code that instantiates the three of them, calls their functions and processed the results. Let's call that:

  • Manager

Well, now Manager is my bottleneck, so I'd like to turn it into a C extension. But I don't know how to instantiate Foo, Bar, and Baz from within Manager. Do I have to use code like:

VALUE module_klass = rb_const_get(rb_cObject, rb_intern("Module"));
VALUE object_klass = rb_const_get(module_klass, rb_intern("Foo"));

And then call methods like:

rb_funcall(object_klass, rb_intern("new"), 0);     

Or is there a cleaner way?

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
Jeremy Smith
  • 14,727
  • 19
  • 67
  • 114

1 Answers1

4

Check out rb_class_new_instance(). You would do something like:

VALUE module_klass = rb_const_get(rb_cObject, rb_intern("Module"));
VALUE foo_klass    = rb_const_get(module_klass, rb_intern("Foo"));
VALUE foo          = rb_class_new_instance(0, NULL, foo_klass);
VALUE data         = rb_funcall(foo, rb_intern("some_foo_method"), ...);
Casper
  • 33,403
  • 4
  • 84
  • 79