【问题标题】:Assigning to nested struct members in Ruby FFI分配给 Ruby FFI 中的嵌套结构成员
【发布时间】:2012-04-03 01:57:27
【问题描述】:

考虑以下两个 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

【问题讨论】:

    标签: ruby struct ruby-ffi


    【解决方案1】:

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

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

    FFI“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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      相关资源
      最近更新 更多