I've been looking through tutorials on how to embed Ruby into a C++ program. I've found out how to define a class through "rb_define_class" and "rb_define_class_under" and methods through "rb_define_method". Now i need a good example that explains how to wrap an existing C++ object (pointer) with a ruby class written in C++. Example:
class MyClass
{
public:
MyClass();
void MyMethod();
};
VALUE myclass_init(VALUE self)
{
// I'd like to create a new MyClass instance and store its pointer inside "self"
}
VALUE myclass_meth(VALUE self)
{
// Now i need to retrieve the pointer to the object and call its method
}
int main(int argc, char* argv[])
{
ruby_init();
ruby_init_loadpath();
VALUE myclass = rb_define_class("MyWrapperClass", rb_cObject);
rb_define_method(myclass, "initialize", (VALUE(*)(...))myclass_init, 0);
rb_define_method(myclass, "myWrappedMethod", (VALUE(*)(...))myclass_meth, 0);
// Loading ruby script skipped..
ruby_finalize();
return 0;
}
I also need a way to handle garbage collection in order to free my wrapped object (and do other stuff). Sorry for the bad english and thanks to whoever will try to answer this question!