4
我想用Ruby C API在模块内定义一个类。然而,我在网上看到的这种做法似乎并不适用于我。具体来说,顶层模块被创建,但在模块内部找不到该类。这是我的C文件:用Ruby C API定义模块中的类
#include <ruby.h>
static VALUE mTree;
static VALUE cNode;
VALUE hello_world(VALUE klass)
{
return rb_str_new2("hello world");
}
void Init_tree()
{
mTree = rb_define_module("Tree");
cNode = rb_define_class_under(mTree, "Node", rb_cObject);
rb_define_method(cNode, "hello_world", hello_world, 0);
}
这里是我的extconf.rb:
require 'mkmf'
create_makefile('tree')
这里是我的测试脚本:
require 'tree'
puts Tree # => Tree
puts Tree::Node # => uninitialized constant Tree::Node (NameError)
任何人可以帮助?
您运行的是什么版本的Ruby的?我正在使用ruby 1.9.3dev(2011-09-23修订版33323)[x86_64-darwin11.0.0]。 – user2398029 2012-02-11 00:41:06
也为我工作。我在Ruby 1.9.2-p0上。 – Brandan 2012-02-11 01:24:37
@louism ruby 1.9.3p0(2011-10-30修订版33570)[x86_64-darwin11.2.0] – 2012-02-11 09:36:34