views:

117

answers:

3

I'm sitting with massive amounts of legacy C code that needs to be converted to Ruby for a project.

I've seen Ruby to C translators online, but not the other way around. Would there be a simple way to approach this particular problem?

+1  A: 

You could:

  1. Write a C interpreter in Ruby (very hard).
  2. Wrap the compiled C code with something like SWIG (much easier).
Marcelo Cantos
+5  A: 

You'll either have to write a C to Ruby translator, which is possible but the effort might not be justifiable, or you could split the C code up into smaller modules that you can create Ruby wrappers for as a first step. Once they're all wrapped in Ruby and the main control flow is done in Ruby, you can write a test harness (both to verify correctness of your replacement code and to aid reverse engineering) and start replacing the C modules with Ruby modules.

The divide & conquer approach should work with regular Ruby if you use the modules as native extensions but obviously this will cause further problems if you're targeting something like JRuby as your runtime environment. If you want to do something similar in JRuby as per your comment, you're looking at wrapping the C modules in JNI and calling through from the JVM that way. Either way will allow your C code to interact with the Ruby code, but the two approaches are not interchangeable.

Neither approach is going to be quick and both are going to be a lot of work.

Timo Geusch
JRuby is the delivery environment. Why would this cause more problems? No wrapping?
Forkrul Assail
@Forkrul: if you can wrap the C code with JNI, at least on your development system, and then call that from JRuby, you will at least be in a position to test as you go along that behavior doesn't change when you replace each chunk of C with a chunk of Ruby. Failing that, you could perhaps perform the port on a different Ruby implementation from your actual platform. If you can find a way of wrapping it, though, then see if it works in production, if so call that "milestone 1", and check again whether the code *really* needs porting. You might weasel out of it :-)
Steve Jessop
Updated the answer in light of the JRuby question.
Timo Geusch
A: 

Programming in C and programming in Ruby bear completely different programming paradigms. So while the old saying that you can write Fortran (or C in this case) code in any language is true, the Ruby code that you would eventually get by machine translation wouldn't be Ruby at all, except syntactically.

So, IMHO, any way other than manual (and done by proficient Rubyists, I might add) would be either impossible, or at least not useful at all.

Mladen Jablanović
Very true, but I need a middle ground since the code base is immense, and as always the implementation was required yesterday.
Forkrul Assail