ruby - 在 Ruby FFI 中分配给嵌套结构成员

标签 ruby struct 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

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

关于ruby - 在 Ruby FFI 中分配给嵌套结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9986175/

相关文章:

ruby - 根据长度读取行

c - 如何搜索struct char c?

C++ const struct &variable 产生缺少的标签名称

python - 如何从二进制文件中读取 block 并使用 Python 或 Perl 解包提取结构?

c - 使用 RubyFFI 从 ruby​​ 停止具有无限循环的 c 函数

ruby - 我可以将 ruby​​ 对象指针传递给 ruby​​-ffi 回调吗?

mysql - ActiveRecord 回滚多个事务

ruby-on-rails - Michael Hartl 的 Rails 3 教程第 7 章中的 : Problem with has_password? 方法

ruby - 为什么 "#{String}"是 Ruby 中的常见习语

ruby - 为什么 gem 不自动编译我的 C 扩展