The problem: I've wrapped some c++ code in python using SWIG. On the python side, I want to take a wrapped c++ pointer and down-cast it to be a pointer to a subclass. I've added a new c++ function to the SWIG .i file that does this down-casting, but when I call it from python, I get a TypeError.
Here are the details:
I have two c++ classes, Base and Derived. Derived is a subclass of Base. I have a third class, Container, which contains a Derived, and provides an accessor to it. The accessor returns the Derived as a const Base&, as shown:
class Container {
public:
const Base& GetBase() const {
return derived_;
}
private:
Derived derived_;
};
I've wrapped these classes in python using SWIG. In my python code, I would like to down-cast the Base reference back down to a Derived. To do this, I've written into the swig .i file a helper function in c++ which does the down-casting:
%inline %{
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
%}
In my python code, I call this down-casting function:
base = container.GetBase()
derived = CastToDerived(base)
When I do so, I get the following error:
TypeError: in method 'CastToDerived', argument 1 of type 'Base *'
Why might this be happening?
For reference, here are the relevant bits of the .cxx file generated by SWIG; namely the original function, and its python-interface-ified doppelganger:
Derived* CastToDerived(Base* base) {
return static_cast<Derived*>(base);
}
// (lots of other generated code omitted)
SWIGINTERN PyObject *_wrap_CastToDerived(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
Base *arg1 = (Base *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject * obj0 = 0 ;
Derived *result = 0 ;
if (!PyArg_ParseTuple(args,(char *)"O:CastToDerived",&obj0)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Base, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "CastToDerived" "', argument " "1"" of type '" "Base *""'");
}
arg1 = reinterpret_cast< Base * >(argp1);
result = (Derived *)CastToDerived(arg1);
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Derived, 0 | 0 );
return resultobj;
fail:
return NULL;
}
Any help would be greatly appreciated.
-- Matt