Module: Fiddle::CStructBuilder

Defined in:
lib/fiddle/struct.rb

Overview

Used to construct C classes (CUnion, CStruct, etc)

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

Class Method Summary collapse

Class Method Details

.create(klass, types, members) ⇒ Object

Construct a new class given a 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 members

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

Example:

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


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/fiddle/struct.rb', line 51

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(<<-EOS, __FILE__, __LINE__+1)
    def new_class.size()
      #{size}
    end
    def new_class.malloc()
      addr = Fiddle.malloc(#{size})
      new(addr)
    end
  EOS
  return new_class
end