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

为什么我从ruby数组中提取的值到我的c扩展名错了?

发布时间:2020-12-17 03:00:40 所属栏目:百科 来源:网络整理
导读:这个方法只是验证我能够正确地看到 ruby数组的元素. static VALUE print_cards(self) VALUE self;{ VALUE cards; int i; cards = rb_ivar_get(self,rb_intern("@cards")); VALUE *ary_ptr = RARRAY_PTR(cards); int ary_length = RARRAY_LEN(cards); for(i=0
这个方法只是验证我能够正确地看到 ruby数组的元素.

static VALUE 
print_cards(self) 
  VALUE self;
{
    VALUE cards;
    int i;

    cards = rb_ivar_get(self,rb_intern("@cards"));
    VALUE *ary_ptr = RARRAY_PTR(cards);
    int ary_length = RARRAY_LEN(cards);

    for(i=0; i< ary_length; i++)
        printf("%dn",ary_ptr[i]);

  return Qnil;
}

void Init_ev() {
    rb_eval_string("require './lib/ev/pair_counter'");
    VALUE PairCounter = rb_path2class("EV::PairCounter");
    rb_define_method(PairCounter,"print_cards",print_cards,0);
}

但是当我使用该方法时,数组的元素是错误的.奇怪的是,它看起来并不像我得到某种地址信息,因为打印的数字大小大致与ruby数组中的数字大小相对应.每次创建新对象并运行print_cards时,数字也是一致的.

ruby-1.9.2-p180 :001 > p = EV::PairCounter.new   #=> #<EV::PairCounter:0x000001046a10f8 @pairs={},@cards=[]>
ruby-1.9.2-p180 :002 > p.add_card(1)   #=> 1
ruby-1.9.2-p180 :003 > p.print_cards
3                                      #=> nil
ruby-1.9.2-p180 :004 > p.add_card(5)   #=> 2
ruby-1.9.2-p180 :005 > p.add_card(88)   #=> 3
ruby-1.9.2-p180 :006 > p
=> #<EV::PairCounter:0x000001046a10f8 @pairs={1=>1,5=>1,88=>1},@cards=[1,5,88]>
ruby-1.9.2-p180 :007 > p.print_cards
3
11
177

解决方法

我需要使用

printf("%dn",NUM2INT(ary_ptr[i]));

(编辑:李大同)

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

    推荐文章
      热点阅读