Monday, January 10, 2011

Writing Ruby Extensions in C - Part 4, Types and Return Values

This is the fourth in my series of posts about writing ruby extensions in C. The first post talked about the basic structure of a project, including how to set up building. The second post talked about generating documentation. The third post talked about initializing the module and setting up classes. This short post will focus on some details of method implementation, including how to check the types that are being passed to extension methods and the legal return values from the extension methods.

Ruby types


When implementing a ruby method in C, the method may expect certain arguments to be of a certain type. For instance, it is possible that the ruby method expects a number, and only a number, as the input parameter. The ruby C extension API provides several functions to check if an input parameter is a certain type:
  • TYPE(ruby_object) - return the builtin type of ruby_object. The builtin types distinguish between things like TrueClass, FalseClass, FIXNUM, etc. It explicitly does not distinguish between complicated object types; use either CLASS_OF() or rb_obj_classname() for that. The builtin types that may be returned are:
    • T_NONE
    • T_NIL
    • T_OBJECT
    • T_CLASS
    • T_ICLASS
    • T_MODULE
    • T_FLOAT
    • T_STRING
    • T_REGEXP
    • T_ARRAY
    • T_FIXNUM
    • T_HASH
    • T_STRUCT
    • T_BIGNUM
    • T_FILE
    • T_TRUE
    • T_FALSE
    • T_DATA
    • T_MATCH
    • T_SYMBOL
    • T_BLKTAG
    • T_UNDEF
    • T_VARMAP
    • T_SCOPE
    • T_NODE
  • NIL_P(ruby_object) - test if ruby_object is the nil object
  • CheckType(ruby_object, builtin_type) - check to make sure that ruby_object is of type builtin_type (one of the T_* types listed above). If it is not, an exception is raised
  • CLASS_OF(ruby_object) - return the ruby class VALUE that corresponds to ruby_object. Note that this can distinguish between built-in class types (such as rb_cSymbol) as well as more complicated class types (such as those defined by the API user)
  • rb_obj_classname(ruby_object) - return the char * string representation of the class corresponding to ruby_object

Return values


Every ruby method implemented in C has to return a VALUE. This VALUE can either be a ruby object (such as that returned by INT2NUM), or one of the special values:
  • Qnil - ruby "nil"
  • Qtrue - ruby "true"
  • Qfalse - ruby "false"

Methods that are expected to either succeed or raise an exception typically return Qnil to indicate success.

No comments:

Post a Comment