为什么我从 ruby 数组提取到 c 扩展的值是错误的?
这个方法只是验证我是否能够正确地看到 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("%d\n", 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
This method is just verifying that I'm able to see the elements of a ruby array correctly.
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("%d\n", 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);
}
But when I put the method to use, the elements of the array are wrong. The strange thing is that it doesn't look like I'm getting some kind of address information, since the size of the number that is printed roughly corresponds with the size of the number in the ruby array. The numbers are also consistent each time I create a new object and run 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我需要使用
I needed to use
rb_ary_entry
是从 Ruby 数组获取内容的安全方法。它们不像普通的 C 数组那样被访问。似乎与这个问题相关:https://stackoverflow.com/a/9619163/486990
rb_ary_entry
is the safe way to get the content from a Ruby array. They are not accessed like normal C arrays.Seems to be related to this question: https://stackoverflow.com/a/9619163/486990