How to write a non-static method in a C ++ class in a Ruby-C ++ extension?

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?

+4
source share
1 answer

C C. () C . https://github.com/TorstenRobitzki/Sioux/blob/master/source/rack/bayeux.cpp, bayeux_server - update_node(), ruby.

http://ruby-doc.com/docs/ProgrammingRuby/ " Ruby". , , Ruby (VALUE), , , . GC, , - , .

extern "C" VALUE newInitialize(VALUE self)
{
    MyClass* s = 0;
    Data_Get_Struct( self, MyClass, s );
    s->newInitialize();
}

reinterpret_cast!

+2

Source: https://habr.com/ru/post/1529234/


All Articles