分配给Ruby FFI中的嵌套结构成员



考虑以下两个FFI结构:

class A < FFI::Struct
layout :data, :int
end 
class B < FFI::Struct
layout :nested, A
end

实例化它们:

a = A.new
b = B.new

现在,当我尝试将a分配给b.nested时,如下所示:

b[:nested] = a

我得到以下错误:

ArgumentError: put not supported for FFI::StructByValue

如果嵌套结构是"按值嵌套"的,也就是说它不是指针,那么FFI似乎不允许使用[]语法进行赋值。如果是,如何将a分配给b.nested

当你使用FFI嵌套时,它可以像这样工作:

b = B.new
b[:nested][:data] = 42
b[:nested][:data] #=> 42

外国金融机构"b"对象创建了自己的"a"对象;你不需要创建自己的。

看起来你想做的是创建自己的"a"对象,然后存储它:

a = A.new
b = B.new
b[:nested] = a  #=> fails because "a" is a Ruby object, not a nested value

一种解决方案是将"A"存储为指针:

require 'ffi'
class A < FFI::Struct
  layout :data, :int
end
class B < FFI::Struct
  layout :nested, :pointer  # we use a pointer, not a class
end
a = A.new
b = B.new
# Set some arbitrary data
a[:data] = 42
# Set :nested to the pointer to the "a" object
b[:nested] = a.pointer
# To prove it works, create a new object with the pointer
c = A.new(b[:nested])
# And prove we can get the arbitrary data    
puts c[:data]  #=> 42

最新更新