2012-04-03 83 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