I use SWIG to wrap a Ruby script around a C++ library. In Ruby, I can inherit from a C++ class, but I cannot pass the resulting pointer to a C++ function in a polymorphic way.
Here is a concrete example. The SWIG interface file defines base class Animal with virtual function sound():
[animals.i]
%module(directors="1") animals
%{
#include "animals.h"
%}
// Apply the 'director' feature to a virtual function,
// so that we can override it in Ruby.
%feature("director") Animal::sound;
class Animal {
public:
Animal();
virtual ~Animal();
virtual void sound();
};
class Dog : public Animal {
public:
Dog();
virtual ~Dog();
virtual void sound();
};
// This function takes an Animal* and calls its virtual function sound().
void kick(Animal*, int);
Note that I use SWIG directors for cross-language polymorphism, but this does not seem to work. The Ruby script looks like this:
[tst.rb]
require 'animals'
include Animals
dog= Dog.new # Instantiate C++ class
kick(dog, 3) # Kick the dog 3 times => It barks 3 times.
# So far so good.
class Cat < Animal # Inherit from a C++ class
def initialize
puts "Creating new cat"
end
def sound
puts "Meow"
end
end
cat= Cat.new # Instantiate Ruby class
kick(cat, 9) # This does not fly.
The final line in the script produces this error:
Expected argument 0 of type Animal *, but got Cat #<Cat:0xb7d621c8>
So somehow SWIG does not allow me to treat the Ruby object as a pointer-to-Animal. Any ideas?