Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

22.2. Using a C Library from Ruby

Credit: Garrett Rooney

Problem

You'd like to use a library in your Ruby program, but the library's implemented in C and there are no bindings.

Solution

Write a Ruby extension that wraps the C library with Ruby classes and methods.

Let's say we want to give a Ruby interface to C's file methods (yes, the File class already does this, but this makes a good example). We want to make it possible to open a disk file and read from it a byte at a time.

Just as in Recipe 22.1, you'll need a C file that implements the actual extension. This one is called stdio.c. It's got an Init_stdio function that defines a Ruby module (Stdio), a Ruby class (Stdio::File), and some methods for that class.

The file_allocate function corresponds to the Stdio::File constructor. Because it's a constructor, we must also define some hook functions to create and destroy the underlying resources (in this case, a filehandle and the memory it uses):

	#include "stdio.h"
	#include "ruby.h"

	static VALUE rb_mStdio;
	static VALUE rb_cStdioFile;

	struct file
	{
	  FILE *fhandle;
	};

	static VALUE
	file_allocate(VALUE klass)
	{
	  struct file *f = malloc(sizeof(*f));
	  f->fhandle = NULL;
	  return Data_Wrap_Struct(klass, file_mark, file_free, f);
	}

	static void
	file_mark(struct file *f)
	{
	}

	static void
	file_free(struct file *f)
	{
	  fclose(f->fhandle);
	  free(f);
	}

The file_open function implements the Stdio::File#open method:

 static VALUE file_open(VALUE object, VALUE fname) { struct file *f; Data_Get_Struct(object, struct ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required