迭代 Ruby FFI 结构布局
我正在使用非常棒的 ruby ffi 库来访问 ruby 中 ac 库中的函数。
有没有办法迭代 Ruby FFI::Struct 的布局?
示例 FFI::Struct:
class Example < FFI::Struct
layout :name, string,
:desc, :string,
:type, :int,
:value, :string
end
这似乎不起作用,但类似于下面的伪代码:
example_struct.each_key do |key|
puts key
end
I am using 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 struct.rb 的源,我发现您可以调用
Struct::members
来获取您定义为“键”的符号数组。从那里,您还可以获得每个成员的值的
Struct::values
、每个成员的偏移量的Struct::offsets
以及一些其他方法。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.当然比遍历 Struct 的成员要昂贵一些,但您也可以使用
to_h
将其转换为哈希。Surely a bit more expensive than iterating through the Struct's members, but you can also convert it to a hash with
to_h
.