【发布时间】:2019-04-08 10:17:42
【问题描述】:
我想在 ruby 中实现我自己的静态数组类。它将是一个具有固定容量的数组,并且数组中的所有元素都是单一类型。 为了直接访问内存,我使用了 FFI gem https://github.com/ffi/ffi,它可以创建您自己的 C 函数并在您的 ruby 程序中使用它们。 我创建了一个非常简单的 C 函数,它为整数数组分配内存并返回指向内存空间的指针:
int * create_static_array(int size) {
int *arr = malloc(size * sizeof(int));
return arr;
}
这是我使用 create_static_array 的 ruby static_array 类:
require 'ffi'
class StaticArray
attr_accessor :pointer, :capacity, :next_index
extend FFI::Library
ffi_lib './create_array/create_array.so'
attach_function :create_static_array, [:int], :pointer
def initialize(capacity)
@capacity = capacity
@pointer = create_static_array(capacity)
@next_index = 0
end
# adds value to the next_index in array
def push(val)
@pointer[@next_index].write(:int, val)
@next_index += 1
end
# reads value at index
def [](index)
raise IndexOutOfBoundException if index >= @capacity
self.pointer[index].read(:int)
end
# print every value in index
def print
i = 0
while (i < @capacity)
puts @pointer[i].read(:int)
i += 1
end
end
end
我添加了几个方法来与我的数组交互、推送元素、读取索引处的元素... 但是我的 static_array 实例并没有按预期工作......
假设我在写:
// creates a static array in memory which can store 4 ints
arr = StaticArray.new(4)
现在让我们在我们的 arr 中推入一个 int :
arr.push(20)
arr.print 将输出
20
0
0
0
这是有道理的。现在让我们将另一个 int 推入 arr :
arr.push(16)
和arr.print 再次:
4116
16
0
0
20 已被 4116 取代......我真的不明白这里发生了什么?
【问题讨论】:
-
你的目标是什么?性能、减少内存使用、与其他本机代码的交互?