21. September, 2007
21. September, 2007
in
»
by Michael Neumann

In my last article I wrote about using Ruby and C to implement a high-performance pulsed neural net simulator. The first result is a library called CplusRuby which makes it easy to mix Ruby and C. Take a look at the README and/or at the following example:

require 'cplusruby'

class NeuralEntity < CplusRuby
  property :id
end

class Neuron < NeuralEntity
  property :potential,        :float
  property :last_spike_time,  :float
  property :pre_synapses,     :value

  method_c :stimulate, %(float at, float weight), %{
    // this is C code
    selfc->potential += at*weight;
  }

  def initialize
    self.pre_synapses = []
  end
end

# generate C file, compile it and load the .so
CplusRuby.evaluate("inspire.cc", "-O3", "-lstdc++")

if __FILE__ == $0
  n = Neuron.new
  n.id = "n1"
  n.potential = 1.0
  n.stimulate(1.0, 2.0)
  p n.potential # => 3.0
end

Note that the crux of CplusRuby is high-performance. The properties form a C structure which is attached to the Ruby object. The C functions can access those values directly, and C functions are itself properties, as such you can call other C method-functions directly without going through Ruby, which is sloooow! On the other hand, you can access everything from Ruby as well. Of course all garbage collecting stuff is generated for you automatically!