Maintenance of Ruby 2.0.0 will end on February 24, 2016. Read more

In Files

  • dl/lib/dl/struct.rb

Methods

DL::CStructBuilder

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

DL::Importer#struct and DL::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 (DL:TYPE_INT, DL::TYPE_SIZE_T, etc., see the C types constants)

  • corresponding members

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

Example:

require 'dl/struct'
require 'dl/cparser'

include DL::CParser

types, members = parse_struct_signature(['int i','char c'])

MyStruct = DL::CStructBuilder.create(CUnion, types, members)

obj = MyStruct.allocate
 
               # File dl/lib/dl/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 = DL.malloc(#{size})
          new(addr)
        end
", __FILE__, __LINE__+1)
      return new_class
    end
            

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus