在线文档教程
Ruby 2.4

Fiddle::CStructBuilder

module Fiddle::CStructBuilder

用于构建C类(CUnion,CStruct等)

Fiddle :: Importer#struct和Fiddle :: Importer#union以易于使用的方式包装此功能。

公共类方法

create(klass, types, members) Show source

构建一个新的类,给出一个C:

  • class klass (CUnion, CStruct, or other that provide an entity_class)

  • types (Fiddle::TYPE_INT, Fiddle::TYPE_SIZE_T, etc., see the C types constants)

  • corresponding membersFiddle::Importer#struct and Fiddle::Importer#union wrap this functionality in an easy-to-use manner.

  • class klass (CUnion, CStruct, or other that provide an entity_class)

  • types (Fiddle::TYPE_INT, Fiddle::TYPE_SIZE_T, etc., see the C types constants)

  • corresponding members

Fiddle :: Importer#struct和Fiddle :: Importer#union以易于使用的方式包装此功能。

例:

require 'fiddle/struct' require 'fiddle/cparser' include Fiddle::CParser types, members = parse_struct_signature(['int i','char c']) MyStruct = Fiddle::CStructBuilder.create(Fiddle::CUnion, types, members) obj = MyStruct.allocate

# File ext/fiddle/lib/fiddle/struct.rb, line 50 def create(klass, types, members) new_class = Class.new(klass){ define_method(:initialize){|addr| @entity = klass.entity_class.new(addr, types) @entity.assign_names(members) } define_method(:to_ptr){ @entity } define_method(:to_i){ @entity.to_i } members.each{|name| define_method(name){ @entity[name] } define_method(name + "="){|val| @entity[name] = val } } } size = klass.entity_class.size(types) new_class.module_eval(" def new_class.size() #{size} end def new_class.malloc() addr = Fiddle.malloc(#{size}) new(addr) end ", __FILE__, __LINE__+1) return new_class end