Swig typecast to derived class?
Posted
by Zack
on Stack Overflow
See other posts from Stack Overflow
or by Zack
Published on 2009-06-08T20:39:24Z
Indexed on
2010/03/08
2:12 UTC
Read the original article
Hit count: 687
I notice that Swig provides a whole host of functions to allow for typecasting objects to their parent classes. However, in C++ one can produce a function like the following:
A * getAnObject()
{
if(someBoolean)
return (A *) new B;
else
return (A *) new C;
}
Where "A" is the parent of classes "B" and "C". One can then typecast the pointer returned into being a "B" type or "C" type at one's convenience like:
B * some_var = (B *) getAnObject();
Is there some way I can typecast an object I've received from a generic-pointer-producing function at run-time in the scripting language using the wrappers? (In my case, Lua?) I have a function that could produce one of about a hundred possible classes, and I'd like to avoid writing an enormous switch structure that I'd have to maintain in C++. At the point where I receive the generic pointer, I also have a string representation of the data type I'd like to cast it to.
Any thoughts? Thanks!
-- EDIT --
I notice that SWIG offers to generate copy constructors for all of my classes. If I had it generate those, could I do something like the following?:
var = myModule.getAnObject(); -- Function that returns an object type-cast down to a pointer of the parent class, as in the function getAnObject() above.
var = myModule.ClassThatExtendsBaseClass(var); -- A copy constructor that SWIG theoretically creates for me
and have var then be an instance of the inheriting class that knows it's an instance of the inheriting class?
© Stack Overflow or respective owner