加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Ruby C API在模块中定义类

发布时间:2020-12-17 02:01:08 所属栏目:百科 来源:网络整理
导读:我试图用 Ruby C API在模块内定义一个类.但是,我在网上看到的这种方式对我来说似乎并不适用.具体来说,顶层模块已创建,但在模块内找不到类.这是我的C档案: #include ruby.hstatic VALUE mTree;static VALUE cNode;VALUE hello_world(VALUE klass){ return rb
我试图用 Ruby C API在模块内定义一个类.但是,我在网上看到的这种方式对我来说似乎并不适用.具体来说,顶层模块已创建,但在模块内找不到类.这是我的C档案:

#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 extconf.rb     
creating Makefile
→ make          
linking shared-object tree.bundle
→ irb
>> $:<<'.'
=> [...]
>> require 'tree'
=> true
>> Tree
=> Tree
>> Tree.class
=> Module
>> Tree::Node.class
=> Class
>> Tree::Node.new.hello_world
=> "hello world"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读