2012-04-03 75 views
3

考虑以下两个FFI结构:分配到嵌套的结构成员在Ruby的FFI

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

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

要实例他们:

a = A.new 
b = B.new 

现在,当我尝试分配ab.nested这样的:

b[:nested] = a 

我收到以下错误:

ArgumentError: put not supported for FFI::StructByValue 

看来FFI不允许你使用[]语法分配,如果嵌套结构是“嵌套的值”,也就是说它不是一个指针。如果是这样,那我该如何分配ab.nested

回答

3

当您使用FFI巢它可以像这样工作:

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

的FFI“B”的对象已经创建了自己的“一”对象;你不需要创建自己的。

什么它看起来就像你试图做的是创建自己的“一”对象,然后存储它:

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

一个解决方案是将“一”为指针:

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 
+0

太棒了。这解决了我的问题。谢谢。 – 2012-04-03 11:05:37