views:

825

answers:

2

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?

+1  A: 

I believe you need to define a helper function that returns a pointer to your instance. I have only used pointers with fopen, so I don't know if this will really work, or if there is something else I am missing. Good luck!

Aram Verstegen
+1  A: 

I got a solution to my problem from Tobias Grimm at the swig-user mailing list. The first part of the problem is SWIG's misleading error message. The message seems to suggest that I pass the wrong type of pointer to my C++ function, but this is not the case. If you check the class of the exception in Ruby, it's ObjectPreviouslyDeleted, meaning that the underlying C struct pointer of my Cat class is NULL. So the real problem is that the pointer is NULL, not that it has the wrong type.

The pointer is NULL because I simply forgot to call "super" in Cat's initialize() method. This way, with the creation of Cat no underlying C struct gets allocated, because the Animal constructor never gets called. Forgetting to call 'super' is a very common Ruby-beginner's mistake, especially for people like me who come from C++, who are used to automatic constructor chaining.

So all I had to do was add a call to 'super':

class Cat < Animal   # Inherit from a C++ class
   def initialize
      puts "Creating new cat"
      super()
   end
   def sound
      puts "Meow"
   end
end

This now works fine. Thanks, Tobias.

Koen Van Damme