I am developing a Ruby-C ++ extension. I have to write a non-static method in the CPP class, and I have to call this class method in the ruby client using an instance of the class.
The following is main.cpp:
#include "ruby.h"
#include <iostream>
using namespace std;
class Mclass
{
public:
int i;
static VALUE newMethod(VALUE self);
static VALUE newInitialize(VALUE self);
};
VALUE Mclass::newMethod(VALUE self)
{
cout<<"It is newMethod() method of class Mclass"<< endl;
return Qnil;
}
VALUE Mclass::newInitialize(VALUE self)
{
cout<<"It is newInitialize() method of class Mclass"<< endl;
return Qnil;
}
extern "C" void Init_Test(){
VALUE lemon = rb_define_module("Test");
VALUE mc = rb_define_class_under(lemon, "Mclass", rb_cObject);
rb_define_method(mc, "new",
reinterpret_cast< VALUE(*)(...) >(Mclass::newMethod), 0);
rb_define_method(mc, "initialize",
reinterpret_cast< VALUE(*)(...) >(Mclass::newInitialize), 0);
}
The following is the ruby client code:
require 'Test'
include Test
a = Mclass.new
I can get an instance of "Mclass" in the ruby client. But you want to call the class a non-static method in the ruby client. How to add non-static method to CPP class?
source
share