为什么 RARRAY_LEN 没有被分配?
我正在使用 C 扩展方法创建一个新的 ruby 数组,但 RARRAY_LEN 未设置。我做错了什么吗?
long int max = 4;
VALUE rAry;
rAry = rb_ary_new2(max);
printf("allocated: %lu\n", RARRAY_LEN(rAry));
输出:
allocated: 0
I'm using the C extension methods to create a new ruby array, but RARRAY_LEN is not getting set. Am I doing something wrong?
long int max = 4;
VALUE rAry;
rAry = rb_ary_new2(max);
printf("allocated: %lu\n", RARRAY_LEN(rAry));
output:
allocated: 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 array.c (Ruby 1.8.6):
#define RARRAY_LEN(s) (RARRAY(s)->len)
RARRAY(s)->len
与Array#length
相同代码>.rb_ary_new2(4)
与Array.new(4)
不同。ARY_DEFAULT_SIZE
定义为16
。它所做的只是为数组分配内存 - 但不填充它。当您知道数组的最终大小时使用它,这样就不必动态调整其大小。
您想要用于实现目的的是
rb_ary_new3
或rb_ary_new4
。来自Ruby 编程:实用程序员指南:
请注意,这些函数要求您为每个元素提供一个值。因此,您需要执行类似以下操作:
rAry = rb_ary_new3(4, Qnil, Qnil, Qnil, Qnil)
来复制Array.new(4)
。如果您提供的参数较少,您会在 Ruby 中得到奇怪的行为。 (没有例外 - 尽管你得到了一个无效的对象。)From
array.c
(Ruby 1.8.6):#define RARRAY_LEN(s) (RARRAY(s)->len)
RARRAY(s)->len
is the same asArray#length
.rb_ary_new2(4)
is not the same asArray.new(4)
.ARY_DEFAULT_SIZE
is defined as16
.What is does is just allocate memory for an array - but doesn't populate it. Use it when you know the final size of your array so it doesn't have to be dynamically re-sized.
What you want to use for your intentions are
rb_ary_new3
orrb_ary_new4
.From Programming Ruby: The Pragmatic Programmer's Guide:
Note that these functions require you to provide a value for each element. So you'd need to do something like:
rAry = rb_ary_new3(4, Qnil, Qnil, Qnil, Qnil)
to replicateArray.new(4)
. If you provided less arguments you'd get strange behavior in Ruby. (No exceptions - despite the fact you get an invalid object.)显然需要使用 rb_ary_store(obj, index, val) 来增加 RARRAY_LEN。奇怪的是,如此重要的方法基本上没有记录。
Apparently rb_ary_store(obj, index, val) needs to be used to increment RARRAY_LEN. It's strange that a method so crucial is basically undocumented.