Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby Programming
Previous Page Home Next Page

Ruby C Language API

Last, but by no means least, here are several C-level functions that you may find useful when writing an extension.

Some functions require an ID: you can obtain an ID for a string by using rb_intern and reconstruct the name from an ID by using rb_id2name.

As most of these C functions have Ruby equivalents that are already described in detail elsewhere in this book, the descriptions here will be brief.

Also note that the following listing is not complete. There are many more functions available---too many to document them all, as it turns out. If you need a method that you can't find here, check ``ruby.h'' or ``intern.h'' for likely candidates. Also, at or near the bottom of each source file is a set of method definitions that describe the binding from Ruby methods to C functions. You may be able to call the C function directly, or search for a wrapper function that calls the function you are looking for. The following list, based on the list in README.EXT, shows the main source files in the interpreter.

Ruby Language Core

class.c error.c eval.c gc.c object.c parse.y variable.c
Utility Functions

dln.c regex.c st.c util.c
Ruby Interpreter

dmyext.c inits.c keywords main.c ruby.c version.c
Base Library

array.c bignum.c compar.c dir.c enum.c file.c hash.c io.c marshal.c math.c numeric.c pack.c prec.c process.c random.c range.c re.c signal.c sprintf.c string.c struct.c time.c

Defining Objects
VALUE� rb_define_class(char *name, VALUE superclass")
Defines a new class at the top level with the given name and superclass (for class Object, use rb_cObject).
VALUE� rb_define_module(char *name")
Defines a new module at the top level with the given name.
VALUE� rb_define_class_under(VALUE under, char *name, VALUE superclass")
Defines a nested class under the class or module under.
VALUE� rb_define_module_under(VALUE under, char *name")
Defines a nested module under the class or module under.
void� rb_include_module(VALUE parent, VALUE module")
Includes the given module into the class or module parent.
void� rb_extend_object(VALUE obj, VALUE module")
Extends obj with module.
VALUE� rb_require(const char *name")
Equivalent to ``require name.'' Returns Qtrue or Qfalse.

In some of the function definitions that follow, the parameter argc specifies how many arguments a Ruby method takes. It may have the following values.

argc Function prototype
0..17 VALUE func(VALUE self, VALUE arg...)
The C function will be called with this many actual arguments.
-1 VALUE func(int argc, VALUE *argv, VALUE self)
The C function will be given a variable number of arguments passed as a C array.
-2 VALUE func(VALUE self, VALUE args)
The C function will be given a variable number of arguments passed as a Ruby array.

In a function that has been given a variable number of arguments, you can use the C function rb_scan_args to sort things out (see below).

Defining Methods
void� rb_define_method(VALUE classmod, char *name, VALUE(*func)(), int argc")
Defines an instance method in the class or module classmod with the given name, implemented by the C function func and taking argc arguments.
void� rb_define_module_function(VALUE classmod, char *name, VALUE(*func)(), int argc)")
Defines a method in class classmod with the given name, implemented by the C function func and taking argc arguments.
void� rb_define_global_function(char *name, VALUE(*func)(), int argc")
Defines a global function (a private method of Kernel) with the given name, implemented by the C function func and taking argc arguments.
void� rb_define_singleton_method(VALUE classmod, char *name, VALUE(*func)(), int argc")
Defines a singleton method in class classmod with the given name, implemented by the C function func and taking argc arguments.
int� rb_scan_args(int argcount, VALUE *argv, char *fmt, ...")
Scans the argument list and assigns to variables similar to scanf: fmt is a string containing zero, one, or two digits followed by some flag characters. The first digit indicates the count of mandatory arguments; the second is the count of optional arguments. A ``*'' means to pack the rest of the arguments into a Ruby array. A ``&'' means that an attached code block will be taken and assigned to the given variable (if no code block was given, Qnil will be assigned). After the fmt string, pointers to VALUE are given (as with scanf) to which the arguments are assigned.

VALUE name, one, two, rest;
rb_scan_args(argc, argv, "12", &name, &one, &two);
rb_scan_args(argc, argv, "1*", &name, &rest);
void� rb_undef_method(VALUE classmod, const char *name")
Undefines the given method name in the given classmod class or module.
void� rb_define_alias(VALUE classmod, const char *newname, const char *oldname")
Defines an alias for oldname in class or module classmod.

Defining Variables and Constants
void� rb_define_const(VALUE classmod, char *name, VALUE value")
Defines a constant in the class or module classmod, with the given name and value.
void� rb_define_global_const(char *name, VALUE value")
Defines a global constant with the given name and value.
void� rb_define_variable(const char *name, VALUE *object")
Exports the address of the given object that was created in C to the Ruby namespace as name. From Ruby, this will be a global variable, so name should start with a leading dollar sign. Be sure to honor Ruby's rules for allowed variable names; illegally named variables will not be accessible from Ruby.
void� rb_define_class_variable(VALUE class, const char *name, VALUE val")
Defines a class variable name (which must be specified with a ``@@'' prefix) in the given class, initialized to value.
void� rb_define_virtual_variable(const char *name, VALUE(*getter)(), void(*setter)()")
Exports a virtual variable to Ruby namespace as the global $name. No actual storage exists for the variable; attempts to get and set the value will call the given functions with the prototypes:

VALUE getter(ID id, VALUE *data,
             struct global_entry *entry);
void setter(VALUE value, ID id, VALUE *data,
            struct global_entry *entry);

You will likely not need to use the entry parameter and can safely omit it from your function declarations.
void� rb_define_hooked_variable(const char *name, VALUE *variable, VALUE(*getter)(), void(*setter)()")
Defines functions to be called when reading or writing to variable. See also rb_define_virtual_variable.
void� rb_define_readonly_variable(const char *name, VALUE *value")
Same as rb_define_variable, but read-only from Ruby.
void� rb_define_attr(VALUE variable, const char *name, int read, int write")
Creates accessor methods for the given variable, with the given name. If read is nonzero, create a read method; if write is nonzero, create a write method.
void� rb_global_variable(VALUE *obj")
Registers the given address with the garbage collector.

Calling Methods
VALUE� rb_funcall(VALUE recv, ID id, int argc, ...")
Invokes the method given by id in the object recv with the given number of arguments argc and the arguments themselves (possibly none).
VALUE� rb_funcall2(VALUE recv, ID id, int argc, VALUE *args")
Invokes the method given by id in the object recv with the given number of arguments argc and the arguments themselves given in the C array args.
VALUE� rb_funcall3(VALUE recv, ID id, int argc, VALUE *args")
Same as rb_funcall2, but will not call private methods.
VALUE� rb_apply(VALUE recv, ID name, int argc, VALUE args")
Invokes the method given by id in the object recv with the given number of arguments argc and the arguments themselves given in the Ruby Array args.
ID� rb_intern(char *name")
Returns an ID for a given name. If the name does not exist, a symbol table entry will be created for it.
char *� rb_id2name(ID id")
Returns a name for the given id.
VALUE� rb_call_super(int argc, VALUE *args")
Calls the current method in the superclass of the current object.

Exceptions
void� rb_raise(VALUE exception, const char *fmt, ...")
Raises an exception. The given string fmt and remaining arguments are interpreted as with printf.
void� rb_fatal(const char *fmt, ...")
Raises a Fatal exception, terminating the process. No rescue blocks are called, but ensure blocks will be called. The given string fmt and remaining arguments are interpreted as with printf.
void� rb_bug(const char *fmt, ...")
Terminates the process immediately---no handlers of any sort will be called. The given string fmt and remaining arguments are interpreted as with printf. You should call this function only if a fatal bug has been exposed. You don't write fatal bugs, do you?
void� rb_sys_fail(const char *msg")
Raises a platform-specific exception corresponding to the last known system error, with the given msg.
VALUE� rb_rescue(VALUE (*body)(), VALUE args, VALUE(*rescue)(), VALUE rargs")
Executes body with the given args. If a StandardError exception is raised, then execute rescue with the given rargs.
VALUE� rb_ensure(VALUE(*body)(), VALUE args, VALUE(*ensure)(), VALUE eargs")
Executes body with the given args. Whether or not an exception is raised, execute ensure with the given rargs after body has completed.
VALUE� rb_protect(VALUE (*body)(), VALUE args, int *result")
Executes body with the given args and returns nonzero in result if any exception was raised.
void� rb_notimplement(")
Raises a NotImpError exception to indicate that the enclosed function is not implemented yet, or not available on this platform.
void� rb_exit(int status")
Exits Ruby with the given status. Raises a SystemExit exception and calls registered exit functions and finalizers.
void� rb_warn(const char *fmt, ...")
Unconditionally issues a warning message to standard error. The given string fmt and remaining arguments are interpreted as with printf.
void� rb_warning(const char *fmt, ...")
Conditionally issues a warning message to standard error if Ruby was invoked with the -w flag. The given string fmt and remaining arguments are interpreted as with printf.

Iterators
void� rb_iter_break(")
Breaks out of the enclosing iterator block.
VALUE� rb_each(VALUE obj")
Invokes the each method of the given obj.
VALUE� rb_yield(VALUE arg")
Transfers execution to the iterator block in the current context, passing arg as an argument. Multiple values may be passed in an array.
int� rb_block_given_p(")
Returns true if yield would execute a block in the current context---that is, if a code block was passed to the current method and is available to be called.
VALUE� rb_iterate(VALUE (*method)(), VALUE args, VALUE (*block)(), VALUE arg2")
Invokes method with argument args and block block. A yield from that method will invoke block with the argument given to yield, and a second argument arg2.
VALUE� rb_catch(const char *tag, VALUE (*proc)(), VALUE value")
Equivalent to Ruby catch.
void� rb_throw(const char *tag , VALUE value")
Equivalent to Ruby throw.

Accessing Variables
VALUE� rb_iv_get(VALUE obj, char *name")
Returns the instance variable name (which must be specified with a ``@'' prefix) from the given obj.
VALUE� rb_ivar_get(VALUE obj, ID name")
Returns the instance variable name from the given obj.
VALUE� rb_iv_set(VALUE obj, char *name, VALUE value")
Sets the value of the instance variable name (which must be specified with a ``@'' prefix) in the given obj to value. Returns value.
VALUE� rb_ivar_set(VALUE obj, ID name, VALUE value")
Sets the value of the instance variable name in the given obj to value. Returns value.
VALUE� rb_gv_set(const char *name, VALUE value")
Sets the global variable name (the ``$'' prefix is optional) to value. Returns value.
VALUE� rb_gv_get(const char *name")
Returns the global variable name (the ``$'' prefix is optional).
void� rb_cvar_set(VALUE class, ID name, VALUE val")
Sets the class variable name in the given class to value.
VALUE� rb_cvar_get(VALUE class, ID name")
Returns the class variable name from the given class.
int� rb_cvar_defined(VALUE class, ID name")
Returns Qtrue if the given class variable name has been defined for class; otherwise, returns Qfalse.
void� rb_cv_set(VALUE class, const char *name, VALUE val")
Sets the class variable name (which must be specified with a ``@@'' prefix) in the given class to value.
VALUE� rb_cv_get(VALUE class, const char *name")
Returns the class variable name (which must be specified with a ``@@'' prefix) from the given class.

Object Status
OBJ_TAINT(VALUE obj")
Marks the given obj as tainted.
int� OBJ_TAINTED(VALUE obj")
Returns nonzero if the given obj is tainted.
OBJ_FREEZE(VALUE obj")
Marks the given obj as frozen.
int� OBJ_FROZEN(VALUE obj")
Returns nonzero if the given obj is frozen.
Check_SafeStr(VALUE str")
Raises SecurityError if current safe level > 0 and str is tainted, or a TypeError if str is not a T_STRING.
int� rb_safe_level(")
Returns the current safe level.
void� rb_secure(int level")
Raises SecurityError if level <= current safe level.
void� rb_set_safe_level(int newlevel")
Sets the current safe level to newlevel.

Commonly Used Methods
VALUE� rb_ary_new(")
Returns a new Array with default size.
VALUE� rb_ary_new2(long length")
Returns a new Array of the given length.
VALUE� rb_ary_new3(long length, ...")
Returns a new Array of the given length and populated with the remaining arguments.
VALUE� rb_ary_new4(long length, VALUE *values")
Returns a new Array of the given length and populated with the C array values.
void� rb_ary_store(VALUE self, long index, VALUE value")
Stores value at index in array self.
VALUE� rb_ary_push(VALUE self, VALUE value")
Pushes value onto the end of array self. Returns value.
VALUE� rb_ary_pop(VALUE self")
Removes and returns the last element from the array self.
VALUE� rb_ary_shift(VALUE self")
Removes and returns the first element from the array self.
VALUE� rb_ary_unshift(VALUE self, VALUE value")
Pushes value onto the front of array self. Returns value.
VALUE� rb_ary_entry(VALUE self, long index")
Returns array self's element at index.
int� rb_respond_to(VALUE self, ID method")
Returns nonzero if self responds to method.
VALUE� rb_thread_create(VALUE (*func)(), void *data")
Runs func in a new thread, passing data as an argument.
VALUE� rb_hash_new(")
Returns a new, empty Hash.
VALUE� rb_hash_aref(VALUE self, VALUE key")
Returns the element corresponding to key in self.
VALUE� rb_hash_aset(VALUE self, VALUE key, VALUE value")
Sets the value for key to value in self. Returns value.
VALUE� rb_obj_is_instance_of(VALUE obj, VALUE klass")
Returns Qtrue if obj is an instance of klass.
VALUE� rb_obj_is_kind_of(VALUE obj, VALUE klass")
Returns Qtrue if klass is the class of obj or class is one of the superclasses of the class of obj.
VALUE� rb_str_new(const char *src, long length")
Returns a new String initialized with length characters from src.
VALUE� rb_str_new2(const char *src")
Returns a new String initialized with the null-terminated C string src.
VALUE� rb_str_dup(VALUE str")
Returns a new String object duplicated from str.
VALUE� rb_str_cat(VALUE self, const char *src, long length")
Concatenates length characters from src onto the String self. Returns self.
VALUE� rb_str_concat(VALUE self, VALUE other")
Concatenates other onto the String self. Returns self.
VALUE� rb_str_split(VALUE self, const char *delim")
Returns an array of String objects created by splitting self on delim.


Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire