See what's going on with flipcode!

This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.


  Calling C Functions From Ruby
  Submitted by

The scripting language Ruby is gaining in popularity, but many developers fear speed issues, or want/need to keep their C code intact. So I wrote a simple example of calling C code(in a .dll/.so) from Ruby. I don't pretend to be a Ruby expert, but hope this code can help other developers out there.

Here is an example in C

We don't need no stinkin copyright!

#if defined (WIN32) # include "windows.h" #define EXPORT_FUNC _declspec (dllexport) #endif

#include "ruby.h"

#ifdef _NO_NUM2DBL_ extern double num2double(val) VALUE val; { struct RFloat* flt; if (NIL_P(val)) return 0; flt = RFLOAT(f_float(0, val)); return flt-value; } #endif

static VALUE Sum(obj,arg1,arg2) VALUE obj,arg1; { double val1 = NUM2DBL(arg1); double val2 = NUM2DBL(arg2); return rb_float_new(val1+val2); }


void InitializeRubber() { mRUBBER = rb_define_module("Rubber"); rb_define_module_function(mRUBBER, "Sum", Sum, 2); rb_define_const(mRUBBER, "TestConst", INT2NUM(38)); }

EXPORT_FUNC void Init_rubber() { InitializeRubber(); }

and here is a simple ruby script to test the binding

#Simple ruby script to test ruby-C binding

require "rubber"

print "Testing\n" print "---------------------------------------------------\n" print "C Constant test : "+Rubber::TestConst.to_s()+"\n" print "C Function test : "+Rubber.Sum(100.75,50).to_s()+"\n"

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.


Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.