C++ 如何在C+中编写非静态方法+;用Ruby-C++;分机?
我正在开发一个Ruby-C++扩展。 我必须在CPP类中编写一个非静态方法,并且 必须使用类实例在ruby客户端中调用该类方法 以下是main.cpp:C++ 如何在C+中编写非静态方法+;用Ruby-C++;分机?,c++,ruby,ruby-c-extension,C++,Ruby,Ruby C Extension,我正在开发一个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 VA
#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客户端中获得“Mclass”的实例。但是我们希望在ruby客户机中调用类非静态方法。
如何在CPP类中添加非静态方法?您必须使用C绑定将函数包装到C函数中。将对象(也称为this)和所有参数传递给该C函数,并调用none-static函数。您可以看一看,其中bayeux_server是一个具有函数update_node()的类,可以从ruby调用该函数 另一个好的起点是“扩展Ruby”一章。基本上,您必须确保垃圾收集器能够访问存储在您自己的类中的所有Ruby对象(值),否则,mark and sweep收集器将删除它们。在测试期间,您可以手动调用GC,查看是否收集了一些不应该收集的对象
extern "C" VALUE newInitialize(VALUE self)
{
MyClass* s = 0;
Data_Get_Struct( self, MyClass, s );
s->newInitialize();
}
不要使用重新解释演员表
extern "C" VALUE newInitialize(VALUE self)
{
MyClass* s = 0;
Data_Get_Struct( self, MyClass, s );
s->newInitialize();
}