开发者

Iterate over Ruby FFI Struct layout

I am us开发者_Go百科ing the really awesome ruby ffi library to access functions in a c library in ruby.

Is there a way to iterate over the layout of a Ruby FFI::Struct?

example FFI::Struct:

class Example < FFI::Struct
  layout :name, string,
         :desc, :string,
         :type, :int,
         :value, :string
end

this doesn't seem to work but something like the below pseudo code:

example_struct.each_key do |key|
  puts key
end


Looking at the source for struct.rb, I found that you can call Struct::members to get an array of the symbols you've defined as "keys".

From there, you've also got Struct::values for the values of each member, Struct::offsets for the offsets of each member, and a few other methods.


Surely a bit more expensive than iterating through the Struct's members, but you can also convert it to a hash with to_h.

Foo = Struct.new(:a, :b, :c)
=> Foo
baz = Foo.new(1,2,3)
=> #<struct Foo a=1, b=2, c=3>
baz.to_h
=> {:a=>1, :b=>2, :c=>3}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜