>>>>> "F" == Fredrik Jagenheim <jagenheim / gmail.com> writes:

F> I had to interface with a C-library that took, among other things, an
F> array of bitmaps as input. Otherwise, I would have done it in Ruby, of
F> course.


svg% cat aa.c
#include "ruby.h"

static VALUE
bm_new(VALUE class)
{
  long* bitmask;
  bitmask = ALLOC(long);
  *bitmask = 0;
  VALUE data = Data_Wrap_Struct(class, 0, free, bitmask);
  return data; 
}

static VALUE
bm_add_bit(VALUE self, VALUE bit)
{
  long* bitmask;
  int int_bit = NUM2INT(bit);
  printf("in to add_bit: %s %s\n", 
      RSTRING(rb_inspect(self))->ptr,
      RSTRING(rb_inspect(bit))->ptr);
  Data_Get_Struct(self, long, bitmask);
  *bitmask |= 1 << int_bit;
  return self; 
}

static VALUE
bm_bit_add(VALUE bit, VALUE self)
{
    return bm_add_bit(self, bit);
}

static VALUE
bm_add_bits(VALUE self, VALUE bits)
{
  printf("in to add_bits: %s\n", RSTRING(rb_inspect(bits))->ptr);
  rb_iterate(rb_each, bits, bm_bit_add, self);
  return self; 
}

static VALUE
bm_value(VALUE self)
{
  long* bitmask;
  Data_Get_Struct(self, long, bitmask);
  return INT2NUM(*bitmask);
}

static VALUE cBitmask;

void Init_aa() {
  cBitmask = rb_define_class("Bitmask", rb_cObject);
  rb_define_singleton_method(cBitmask, "new", bm_new, 0);
  rb_define_method(cBitmask, "add_bit", bm_add_bit, 1);
  rb_define_method(cBitmask, "add_bits", bm_add_bits, 1);
  rb_define_method(cBitmask, "value", bm_value, 0);
}
svg% 

svg% cat b.rb
#!/usr/bin/ruby
require 'aa'

bm = Bitmask.new
bm.add_bit(2)
bm.add_bit(4)
puts bm.value

bm = Bitmask.new
bm.add_bits([2, 4])
puts bm.value

svg% 

svg% b.rb
in to add_bit: #<Bitmask:0x40099cf0> 2
in to add_bit: #<Bitmask:0x40099cf0> 4
20
in to add_bits: [2, 4]
in to add_bit: #<Bitmask:0x40099c64> 2
in to add_bit: #<Bitmask:0x40099c64> 4
20
svg% 


Guy Decoux