Fixed a bug in Ruby's object tracking functionality. Previously, an object could be returned even if it did not have the correct type. This could occur if a factory class' creation method had a signature returning a base type (like geometry) but in reality a subclass (like Point) was returned. In that case, it would then be impossible to implement a "downcast" method and get back a Ruby object of type Point. Also updated the test-suite to test this situation.

git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/trunk@8861 626c5289-ae23-0410-ae9c-e8d60b6d4f22
This commit is contained in:
Charlie Savage 2006-02-22 08:20:48 +00:00
commit aff76328a7
3 changed files with 81 additions and 16 deletions

View file

@ -18,6 +18,10 @@
%apply SWIGTYPE *DISOWN {Foo* ownedFoo}; %apply SWIGTYPE *DISOWN {Foo* ownedFoo};
%trackobjects ItemA;
%trackobjects ItemB;
%inline %{ %inline %{
class Foo class Foo
@ -92,4 +96,30 @@ public:
unowned_ = foo; unowned_ = foo;
} }
}; };
class ItemA
{
};
class ItemB: public ItemA
{
public:
};
ItemB* downcast(ItemA* item)
{
return static_cast<ItemB*>(item);
}
class Factory
{
public:
Factory() {}
ItemA* createItem()
{
return new ItemB;
}
};
%} %}

View file

@ -78,3 +78,29 @@ foo14 = bar.get_owned_foo_by_argument()
test_same_ruby_object(foo13, foo14) test_same_ruby_object(foo13, foo14)
test_same_cpp_object(foo13, foo14) test_same_cpp_object(foo13, foo14)
# Now create the factory
factory = Track_objects::Factory.new
# Create itemA which is really an itemB
itemA = factory.createItem
# Check class
if itemA.class != Track_objects::ItemA
raise RuntimeError, 'Item should have an ItemA class'
end
# Now downcast
itemB = Track_objects.downcast(itemA)
if itemB.class != Track_objects::ItemB
raise RuntimeError, 'Item should have an ItemB class'
end
if itemA.eql?(itemB)
raise RuntimeError, 'Items should be different'
end

View file

@ -149,10 +149,19 @@ SWIG_Ruby_NewPointerObj(void *ptr, swig_type_info *type, int flags)
/* Are we tracking this class and have we already returned this Ruby object? */ /* Are we tracking this class and have we already returned this Ruby object? */
if (sklass->trackObjects) { if (sklass->trackObjects) {
obj = SWIG_RubyInstanceFor(ptr); obj = SWIG_RubyInstanceFor(ptr);
/* Check the object's type and make sure it has the correct type.
It might not in cases where methods do things like
downcast methods. */
if (obj != Qnil) { if (obj != Qnil) {
VALUE value = rb_iv_get(obj, "__swigtype__");
char* type_name = RSTRING(value)->ptr;
if (strcmp(type->name, type_name) == 0) {
return obj; return obj;
} }
} }
}
/* Create a new Ruby object */ /* Create a new Ruby object */
obj = Data_Wrap_Struct(sklass->klass, VOIDFUNC(sklass->mark), (own ? VOIDFUNC(sklass->destroy) : 0), ptr); obj = Data_Wrap_Struct(sklass->klass, VOIDFUNC(sklass->mark), (own ? VOIDFUNC(sklass->destroy) : 0), ptr);