【问题标题】:How to write non-static method in C++ class in Ruby-C++ extension?如何在 Ruby-C++ 扩展的 C++ 类中编写非静态方法?
【发布时间】:2014-02-27 15:25:03
【问题描述】:

我正在开发一个 Ruby-C++ 扩展。 我必须在 CPP 类中编写一个非静态方法,我 必须使用类实例在 ruby​​ 客户端中调用该类方法。

以下是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);
}

以下是 ruby​​ 客户端代码:

require 'Test'
include Test

a = Mclass.new

我能够在 ruby​​ 客户端中获取“Mclass”的实例。但是要在 ruby​​ 客户端中调用类非静态方法。 如何在 CPP 类中添加非静态方法?

【问题讨论】:

    标签: c++ ruby ruby-c-extension


    【解决方案1】:

    您必须使用 C 绑定将您的函数包装在 C 函数中。将对象(又名 this)和所有参数传递给该 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

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多