Hi!
Slowly but surly, I'm getting my foot on the ground with embedding Ruby in a C++ application.
So far I can call methods of C++ -classes from the ruby script (using SWIG) and ruby-stuff from C++ using rb_eval_string_protect.
Now I would like to derive a C++-Class in a Ruby script, override a virtual method of the C++ class, return an instance of this new class back to C++ and then invoke the overridden method. I've no idea, if this is possible at all.
See this example and what happens:
[C++:]
class Foo
{
public:
virtual char *bar(void) { return "C++ implementation" };
};
[Ruby:]
class FooBar < MyModul::Foo
def bar
return "Ruby implementation"
end
end
test = Foo.new
$uglyGlobal = FooBar.new
STDERR.puts("Ruby-Foo: ", test.bar)
STDERR.puts("Ruby-FooBar: ", $uglyGlobal.bar)
[Back in C++:]
// ...
// initializing ruby and making SWIG-wrapper available
// ...
rb_load_protect(rb_str_new2("test.rb"), Qfalse, &state);
VALUE obj = rb_eval_string_protect("$uglyGlobal", &state);
Foo fooFromCpp = new Foo();
Foo fooFromRuby = *reinterpret_cast<Foo *>(obj);
cerr << "C++-Foo: " << fooFromCpp.bar() << endl;
cerr << "C++-FooBar: " << fooFromRuby.bar() << endl;
[The output is:]
Ruby-Foo: C++ implementation
Ruby-FooBar: Ruby implementation
C++-Foo: C++ implementation
C++-FooBar: C++ implementation
Obviously C++ does not see, that the FooBar object returned by Ruby has overriden bar(). Am I doing something completely wrong?
I'm not sure how polymorphism is implemented in gcc, but I'm afraid something like this is simply not possible, is it?
bye,
Tobias