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
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

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




Ruby Programming
Previous Page Home Next Page

Embedding a Ruby Interpreter

In addition to extending Ruby by adding C code, you can also turn the problem around and embed Ruby itself within your application. Here's an example.

#include "ruby.h"

main() {   /* ... our own application stuff ... */   ruby_init();   ruby_script("embedded");   rb_load_file("start.rb");   while (1) {     if (need_to_do_ruby) {       ruby_run();     }     /* ... run our app stuff */   } }

To initialize the Ruby interpreter, you need to call ruby_init(). But on some platforms, you may need to take special steps before that:

#if defined(NT)
  NtInitialize(&argc, &argv);
#if defined(__MACOS__) && defined(__MWERKS__)
  argc = ccommand(&argv);

See main.c in the Ruby distribution for any other special defines or setup needed for your platform.

Embedded Ruby API
void� ruby_init(")
Sets up and initializes the interpreter. This function should be called before any other Ruby-related functions.
void� ruby_options(int argc, char **argv")
Gives the Ruby interpreter the command-line options.
void� ruby_script(char *name")
Sets the name of the Ruby script (and $0) to name.
void� rb_load_file(char *file")
Loads the given file into the interpreter.
void� ruby_run(")
Runs the interpreter.

You need to take some special care with exception handling; any Ruby calls you make at this top level should be protected to catch exceptions and handle them cleanly. rb_protect, rb_rescue, and related functions are documented on page 192.

For an example of embedding a Ruby interpreter within another program, see also eruby, which is described beginning on page 147.
Ruby Programming
Previous Page Home Next Page

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