Module: Fiddle::CStructBuilder (Ruby 2.3.7)
Description: Module : Fiddle::CStructBuilder - Ruby 2.3.7

- Home
- Core 2.3.7
- Std-lib 2.3.7
- Downloads

Support for the Ruby 2.3 series has ended. See here for reference.

### Home Classes Methods

### In Files

- fiddle/lib/fiddle/struct.rb

### Methods

- ::create

### Class/Module Index

Quicksearch

- Fiddle
- Fiddle::BasicTypes
- Fiddle::CParser
- Fiddle::CStruct
- Fiddle::CStructBuilder
- Fiddle::CStructEntity
- Fiddle::CUnion
- Fiddle::CUnionEntity
- Fiddle::Closure
- Fiddle::Closure::BlockCaller
- Fiddle::CompositeHandler
- Fiddle::DLError
- Fiddle::Function
- Fiddle::Handle
- Fiddle::Importer
- Fiddle::Pointer
- Fiddle::Win32Types

No matching classes.

# Fiddle::CStructBuilder

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

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

### Public Class Methods

create(klass, types, members) click to toggle source

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

                   # File 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(<<-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