简体   繁体   English

如何在Ruby-C ++扩展中编写C ++类中的非静态方法?

[英]How to write non-static method in C++ class in Ruby-C++ extension?

I'm developing a Ruby-C++ extension. 我正在开发一个Ruby-C ++扩展。 I have to write a non-static method in a CPP class and I have to invoke that class method in ruby client by using the class instance. 我必须在CPP类中编写一个非静态方法,我必须使用类实例在ruby客户端中调用该类方法。

Following is the main.cpp: 以下是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);
}

Also following is the ruby client code: 以下是ruby客户端代码:

require 'Test'
include Test

a = Mclass.new

I'm able to get instance of "Mclass" in ruby client. 我能够在ruby客户端获得“Mclass”的实例。 But want invoke the class non-static method in the ruby client. 但是想在ruby客户端中调用类非静态方法。 How can I add the non-static method in CPP class? 如何在CPP类中添加非静态方法?

You have to wrap your function in C function with C binding. 您必须使用C绑定将函数包装在C函数中。 Pass the object (aka this) and all arguments to that C function and call the none static function. 将对象(也称为this)和所有参数传递给该C函数并调用none静态函数。 You can have a look at https://github.com/TorstenRobitzki/Sioux/blob/master/source/rack/bayeux.cpp , where bayeux_server is a class with a function update_node() that can be called from ruby. 你可以看看https://github.com/TorstenRobitzki/Sioux/blob/master/source/rack/bayeux.cpp ,其中bayeux_server是一个带有函数update_node()的类,可以从ruby调用。

An other good starting point is http://ruby-doc.com/docs/ProgrammingRuby/ chapter "Extending Ruby". 另一个好的起点是http://ruby-doc.com/docs/ProgrammingRuby/章节“扩展Ruby”。 Basicaly, you have to make sure, that garbage collector can reach all Ruby objects (VALUEs) that are stored in your own class, or otherwise, the mark and sweep collector will remove them. 基本上,您必须确保垃圾收集器可以访问存储在您自己的类中的所有Ruby对象(VALUE),否则,标记和扫描收集器将删除它们。 During your tests, you could manually call the GC to see if some objects get collected that shouldn't get collected. 在测试期间,您可以手动调用GC以查看是否收集了一些不应收集的对象。

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

Don't use reinterpret_cast ! 不要使用reinterpret_cast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM