假设我有以下使用FFI库的ruby代码:
class SimpleStruct < FFI::Struct
layout :value, :pointer
end
class Test1
def self.foo(s)
result = FFI::MemoryPointer.from_string(s)
result
end
def self.bar(s)
simple_struct = SimpleStruct.new
value = FFI::MemoryPointer.from_string(s)
simple_struct[:value] = value
simple_struct
end
end
class Test2
def self.testing
a = Test1.foo('test')
b = Test1.bar('test')
puts a.read_string, b[:value].read_string
end
end
FFI wiki提到了When a MemoryPointer goes out of scope, the memory is freed up as part of the garbage collection process
。在上面的Test1
类中,foo
方法返回MemoryPointer,bar
方法返回保存MemoryPointer的FFI结构体。Test2
类中的testing
方法调用这些方法,并将返回值分别存储在变量a
和b
中。
我的问题是,在这种情况下,在foo
和bar
方法中创建的MemoryPointer何时会被垃圾收集?是当MemoryPointer变量在foo
和bar
方法中超出作用域时,还是当局部变量a
或b
(引用从foo
/bar
方法返回的MemoryPointer)在testing
方法中超出作用域时?
1条答案
按热度按时间az31mfrm1#
我相信
FFI::Struct#[]=
会处理这个问题。我没有在源代码中检查它,但我在代码中添加了一些检查,看起来是这样的。指针只有在结构体被垃圾回收时才被垃圾回收,就像散列一样。