我使用 SWIG 将 Ruby 脚本包装在 C++ 库周围。在 Ruby 中,我可以从 C++ 类继承,但不能以多态方式将结果指针传递给 C++ 函数。
这是一个具体的例子。SWIG 接口文件定义了具有虚函数 sound() 的基类 Animal:
[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);
请注意,我将 SWIG 导向器用于跨语言多态性,但这似乎不起作用。Ruby 脚本如下所示:
[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.
脚本中的最后一行产生了这个错误:
Expected argument 0 of type Animal *, but got Cat #<Cat:0xb7d621c8>
所以不知何故 SWIG 不允许我将 Ruby 对象视为指向动物的指针。有任何想法吗?