I am a new Ruby programmer and have been looking through some tutorials for writing a C code extension to the Ruby language and I was wondering: what is the benefit of doing this? I personally was looking at this since I will have to do a team project in the future for a class I am in and I am pretty sure I’m the only person doing Ruby development, but most people know C so I could have them write C code that I could use within my own Ruby development for the project theoretically. But typically, is this the main reason to do it or is there something I am unaware of? Also, would my idea work in your opinion (having someone do C development while I integrate that into Ruby for an overall project)? Can you do something similar with other languages (ie. can you use Java code with a Ruby project, Python code, etc.)?
Share
The primary reasons to do so are speed and re-use of existing functionality.
First, speed. C is generally much, much faster than Ruby, because you avoid the Ruby VM and can do manual memory management. In performance-critical pieces of your applications (like a database driver, for instance), this can mean drastic improvements in overall application runtime, primarily because you aren’t generating a ton of Ruby objects to wrap primitives, and don’t have to invoke the garbage collector to clean up after yourself.
Second, by writing a C extension, you can interface with code that already exists in C libraries. The Linux ecosystem is flush with powerful, well-tested C libraries for lots of common functionality. For example, Nokogiri uses libxml for its parsing, which lets it use a battle-tested and fast parser, and then it just adds the nice Ruby sugar on top. The primary purpose of a C extension in this case is to provide a Ruby API which invokes the C code and translates data to and from C-Ruby data types (so you might pass in an
rb_stringas a parameter, which has to be translated to achar*for consumption by some C library, and then convert the result back to anrb_stringto be passed back to Ruby, for example).When using MRI (stock Ruby), you’re generally limited to just C code, though there are ways of running Python in Ruby and whatnot, but it’s not the same type of interface. If you use JRuby, you can use Java packages directly – no special extension is necessary!
That said, if you’re looking to interface Ruby to an existing C library, take a look at ruby-ffi. It provides a lot of functionality that makes writing an interface to a C library very easy, and may get you up and running quickly and easily.